Maas
Maas

Reputation: 381

Selecting specific object with Json.NET (SelectToken)

I'm new to Json.NET and try out using the SelectToken function.

My test JSON:

{
  "Root": {
    "aNode": {
      "bNode": {
        "cNode": {
          "id": "myID1"
        }
      },
      "cNode": {
        "id": "myID2"
      },
      "dNode": {
        "cNode": [
          {
            "id": "myID3"
          },
          {
            "id": "myID4"
          }
        ]
      }
    },
    "cNode": {
      "id": "myID5"
    }
  }
}

Now, I'm trying to use the following code for getting specific objects:

JObject obj = JsonConvert.DeserializeObject<JObject>(jsonTxt);

//Not found
var myID1 = obj.SelectToken("..cNode[?(@.id=='myID1')]");

//Not found
var myID2 = obj.SelectToken("..cNode[?(@.id=='myID2')]");

//Found
var myID3 = obj.SelectToken("..cNode[?(@.id=='myID3')]");

//Found
var myID4 = obj.SelectToken("..cNode[?(@.id=='myID4')]");

//Not found
var myID5 = obj.SelectToken("..cNode[?(@.id=='myID5')]");

Why do I get these (for me) strange results?

I think I should get in every case the cNode object with the specific ID, and not only myID3 and myID4. What's wrong here?

Upvotes: 2

Views: 1718

Answers (1)

EZI
EZI

Reputation: 15354

I am not sure what you really want to achieve but you can use Linq to get cNodes

var nodes = obj.Descendants()
                .OfType<JProperty>()
                .Where(p => p.Name == "id")
                .Select(p=>p.Parent)
                .ToList();

Upvotes: 3

Related Questions