JSON.NET Parse with JObject, JToken and JArray

[亡魂溺海] 提交于 2019-12-22 09:13:57

问题


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:


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"}]}
}


来源:https://stackoverflow.com/questions/22252647/json-net-parse-with-jobject-jtoken-and-jarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!