C#直接解析Json键值对

2021-04-03 09:24

阅读:431

标签:var   box   children   show   and   序列化   TE   .com   dns   

string test_json = "{\"name\":\"tom\",\"nickname\":\"tony\",\"sex\":\"male\",\"age\":20,\"email\":\"123@123.com\"}";  
    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键值对

标签:var   box   children   show   and   序列化   TE   .com   dns   

原文地址:https://www.cnblogs.com/cuihongyu3503319/p/9204455.html


评论


亲,登录后才可以留言!