C#直接解析Json键值对
Posted 陋室铭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#直接解析Json键值对相关的知识,希望对你有一定的参考价值。
string test_json = "{"name":"tom","nickname":"tony","sex":"male","age":20,"email":"[email protected]"}"; var o = JObject.Parse(yourJsonString); foreach (JToken child in o.Children()) { var property1 = child as JProperty; MessageBox.Show(property1.Name + ":" + property1.Value); } 多层Json var o = JObject.Parse(yourJsonString); foreach (JToken child in o.Children()) { //var property1 = child as JProperty; //MessageBox.Show(property1.Name + ":" + property1.Value); foreach (JToken grandChild in child) { foreach (JToken grandGrandChild in grandChild) { var property = grandGrandChild as JProperty; if (property != null) { MessageBox.Show(property.Name + ":" + property.Value); } } } }
用Newtonsoft.Json.dll
string
str =
@"{
""data"":
{
""mobile"":
{
""platform"":""2.2"",
""model"":""generic|sdk"",
""versioncode"":""20111125"",
""versionname"":""1.2.0"",
""web_domain"":""http://www.baidu.com"",
""ip"":"""",
""dns1"":"""",
""dns2"":"""",
""channel_id"":""0""
}
}
}"
;
javascriptObject json = (JavaScriptObject)JavaScriptConvert.DeserializeObject(str);
JavaScriptObject data = (JavaScriptObject)json[
"data"
];
JavaScriptObject mobile = (JavaScriptObject)data[
"mobile"
];
Console.WriteLine(
"{0} {1} {2}"
, mobile[
"platform"
], mobile[
"model"
], mobile[
"versioncode"
]);
当然,如果有承接类也可以直接反序列化成承接类。
以上是关于C#直接解析Json键值对的主要内容,如果未能解决你的问题,请参考以下文章