在 C# 中动态地从 JSON 中删除节点

Remove Node From JSON dynamically in C#

我需要在 C# 中动态地从 JSON 中删除节点,而不知道节点在 josn 中的实际路径。只需使用 URL 删除节点和 return 删除节点后的 json 查询参数中的值。

 public IHttpActionResult mockErrorCandidateResponse()
        {
            HttpContext currentContext = HttpContext.Current;
            KeysCollection keys = currentContext.Request.QueryString.Keys;
            string key = keys[0];
            string node =  currentContext.Request.QueryString[key];

            //creating the final response
            HttpResponseMessage result = new HttpResponseMessage();
            result.StatusCode = HttpStatusCode.BadRequest;
            string pathToContent = "~/mockCandidateResponse.json"; //relative path to fetch the file
            string actualStrContent = null;
            if (!String.IsNullOrEmpty(pathToContent))
            {
                actualStrContent = Util.getResource(pathToContent);
                result.Content = new StringContent(actualStrContent, Encoding.UTF8, "application/json");
            }
            JObject data = JObject.Parse(actualStrContent); //parsing the json dynamically
              data.SelectToken(node).Remove();
            actualStrContent = data.ToString();
            return ResponseMessage(result);
}

这里是示例JSON


{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

当我查询 GET http://basecandidateurl.com?nodename=**GlossDiv** 时,它应该删除下面的所有内容 GlossDiv 和 return


{
    "glossary": {
        "title": "example glossary"}
}

感谢任何帮助。提前致谢!

这对我有用:

var json = @"{
    'glossary': {
        'title': 'example glossary',
        'GlossDiv': {
            'title': 'S',
            'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                    'SortAs': 'SGML',
                    'GlossTerm': 'Standard Generalized Markup Language',
                    'Acronym': 'SGML',
                    'Abbrev': 'ISO 8879:1986',
                    'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                        'GlossSeeAlso': ['GML', 'XML']
                    },
                    'GlossSee': 'markup'
                }
            }
        }
    }
}";

var nodeToRemove = "GlossDef";

// Step 01: Parse json text
JObject jo = JObject.Parse(json);

// Step 02: Find Token in JSON object
JToken tokenFound = jo.Descendants()
    .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == nodeToRemove)
    .Select(p => ((JProperty)p).Value)
    .FirstOrDefault();

// Step 03: if the token was found select it and then remove it
if (tokenFound != null)
{
    var token = jo.SelectToken(tokenFound.Path);

    token.Parent.Remove();
}

json = jo.ToString();

returns json 字符串:

{
  "glossary": {
    "title": "example glossary"
  }
}

我使用了 Json.Net 库,您可以通过搜索 Newtonsoft.Json

将其嵌入到您的项目中