JSON.NET如何删除节点



我有一个json,如下所示:

{
  "d": {
    "results": [
      {
        "__metadata": {
        },
        "prop1": "value1",
        "prop2": "value2",
        "__some": "value"
      },
      {
        "__metadata": {
        },
        "prop3": "value1",
        "prop4": "value2",
        "__some": "value"
      },
    ]
  }
}

我只想把这个JSON转换成一个不同的JSON。我想从JSON中去掉"_元数据"one_answers"_some"节点。我使用的是JSON.NET.

我刚刚反序列化到JObject,并递归地循环通过它来删除不需要的字段。以下是感兴趣的人的功能。

private void removeFields(JToken token, string[] fields)
{
    JContainer container = token as JContainer;
    if (container == null) return;
    List<JToken> removeList = new List<JToken>();
    foreach (JToken el in container.Children())
    {
        JProperty p = el as JProperty;
        if (p != null && fields.Contains(p.Name))
        {
            removeList.Add(el);
        }
        removeFields(el, fields);
    }
    foreach (JToken el in removeList)
    {
        el.Remove();
    }
}

在@[Mhamed Nuur]的答案的基础上,我将其改为一种我认为效果更好的扩展方法:

 public static JToken RemoveFields(this JToken token, string[] fields)
    {
        JContainer container = token as JContainer;
        if (container == null) return token;
        List<JToken> removeList = new List<JToken>();
        foreach (JToken el in container.Children())
        {
            JProperty p = el as JProperty;
            if (p != null && fields.Contains(p.Name))
            {
                removeList.Add(el);
            }
            el.RemoveFields(fields);
        }
        foreach (JToken el in removeList)
        {
            el.Remove();
        }
        return token;
    }

这是单元测试:

[TestMethod]
     public void can_remove_json_field_removeFields()
     {
        string original = "{"d":{"results":[{"__metadata":{},"remove":"done","prop1":"value1","prop2":"value2","__some":"value"},{"__metadata":{},"prop3":"value1","prop4":"value2","__some":"value"}],"__metadata":{"prop3":"value1","prop4":"value2"}}}";
        string expected = "{"d":{"results":[{"prop1":"value1","prop2":"value2","__some":"value"},{"prop3":"value1","prop4":"value2","__some":"value"}]}}";
        string actual = JToken.Parse(original).RemoveFields(new string[]{"__metadata", "remove"}).ToString(Newtonsoft.Json.Formatting.None);
        Assert.AreEqual(expected, actual);
     }

我将创建一个只包含所需信息的新数据结构,并从第一个结构复制数据。这通常是最简单的方法。只是个主意。

如果您有一个带有JTokens而不是JObjects:的JArray,则此答案适用

这里有一个例子:

string json = "[null, null, "x", null, null, null, 0,[],[["x"], null,[0],["x"]]]";
    JArray array = JArray.Parse(json);
    // Keep first 3 elements, remove the rest
    int max = array.Count;
    for (int i = 0; i < max - 3; i++)
    {
        JToken elem = array[3];
        array.Remove(elem);
    }
    json = array.ToString(Newtonsoft.Json.Formatting.None);
    Console.WriteLine(json);

相关内容

  • 没有找到相关文章

最新更新