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键值对)