JSON.NET how to remove nodes

Viewed 35656

I have a json like the following:

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

I just want to transform this JSON into a different JSON. I want to strip out the "_metadata" and "_some" nodes from the JSON. I'm using JSON.NET.

4 Answers

This answer applies if you have a JArray with JTokens, not JObjects:

Here is an example:

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);
Related