JSON.NET Parse with JObject, JToken and JArray

2019-05-05 17:53发布

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?

1条回答
Summer. ? 凉城
2楼-- · 2019-05-05 18:38

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"}]}
}
查看更多
登录 后发表回答