1. 程式人生 > >C#中對於json格式資料的處理

C#中對於json格式資料的處理

基本環境


vs2013
.NetFramework4.5
名稱空間:using Newtonsoft.Json.Linq


Json字串不知道key值如何獲得value

//假設瀏覽器返回的資料如下:
    string response={"672": 
        {"id": "672", 
        "level":0,
        "children":[
        "b9185a050d0540fea32cdd6fdf5e0d7d",
        "727dc5216f504174a30475f268a616f8",
        "57c8e7da25a34bee832d8fd2cfeed5c1"]
        }
    }12345678910

但是我們不知道“672”這個key的值,他是瀏覽器隨機返回的,這種情況,可以採用如下的方式,使用JProperty:

JObject json = JObject.Parse(response); 

//得到json對應的propertyies,實際是一個<key,value>
物件組成的陣列,可以遍歷和獲得value的值
IEnumerable<JProperty> properties = json.Properties(); 

// 遍歷Jproperty物件
foreach(JProperty item in properties) 
{
   //得到value並轉化為object物件,得到子json
   JObject node = JObject.Parse(item.Value.ToString()); 

}12345678910111213

獲得Json字串中的陣列

同樣是上文中的response,由於children是一個數組,可以採用JToken物件獲得陣列物件並進行遍歷;程式碼如下(接上文程式碼):

JToken children =node["children"];
foreach(JProperty child in children)
{
   // 即可得到字串"b9185a050d0540fea32cdd6fdf5e0d7d"等
   string name = (string)child;
}
--------------------- 

原文:https://blog.csdn.net/pinebud55/article/details/51509447