Lord Vermillion
Lord Vermillion

Reputation: 5424

JSON.NET Parse with JObject, JToken and JArray

I have a json string that i'm trying to parse with JSON.net, i want to loop and use the names in the komponent array. This is my json string:

{"Name": "Service","jsonTEMPLATE": "{"komponent": [{"name": "aa"}, {"name": "bb"}]}"}

This is my code using JSON.net

    JObject o = JObject.Parse(serviceData);
    JToken j = (JToken)o.SelectToken("jsonTEMPLATE");
    JArray a = (JArray)j.SelectToken("komponent");

    foreach (JObject obj in a)
    {
        //Do something
    }

i get null from (JArray)j.SelectToken("komponent");

What am i doing wrong?

Upvotes: 4

Views: 17301

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129707

Your JSON is invalid. You can run it through JSONLint.com to check it. You have quotes around the value of the jsonTEMPLATE property, which should not be there if it is to interpretted as an object:

{
    "Name": "Service",
    "jsonTEMPLATE": "{"komponent": [{"name": "aa"}, {"name": "bb"}]}"
}

The JSON needs to look like this for your code to succeed:

{
    "Name": "Service",
    "jsonTEMPLATE": {"komponent": [{"name": "aa"}, {"name": "bb"}]}
}

Upvotes: 8

Related Questions