Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 454
Lord Vermillion Avatar asked Feb 13 '23 14:02

Lord Vermillion


1 Answers

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"}]}
}
like image 96
Brian Rogers Avatar answered Feb 16 '23 03:02

Brian Rogers