2015-12-08 76 views
0

我有一個如下的JSON對象,這是大多數情況下沒有特定結構的時候。這是從客戶端使用jQuery創建並通過AJAX發送到服務器端。從VB.NET中的Clientside循環遍歷動態JSON對象中的所有屬性

{ 
    "items": { 
     "1": [{ 
      "text": "Man", 
      "itemID": "1", 
      "checked": 1, 
      "sequence": 1, 
      "matchingtext": "", 
      "weight": 0 
     }, { 
      "text": "goat", 
      "itemID": "2", 
      "checked": 0, 
      "sequence": 2, 
      "matchingtext": "", 
      "weight": 0 
     }, { 
      "text": "dog", 
      "itemID": "3", 
      "checked": 0, 
      "sequence": 3, 
      "matchingtext": "", 
      "weight": 0 
     }], 
     "2": [{ 
      "text": "pizza", 
      "itemID": "1", 
      "checked": 1, 
      "sequence": 1, 
      "matchingtext": "", 
      "weight": 0 
     }, { 
      "text": "horse", 
      "itemID": "2", 
      "checked": 0, 
      "sequence": 2, 
      "matchingtext": "", 
      "weight": 0 
     }, { 
      "text": "paper", 
      "itemID": "3", 
      "checked": 0, 
      "sequence": 3, 
      "matchingtext": "", 
      "weight": 0 
     }] 
    }, 
    "wbmode": "dd", 
    "wbanswertype": "sc" 
} 

由於它沒有任何特定的結構,我不能使用某些結構化的類對它進行反序列化。

因此,如何能我會橫越的項目所有的對象,如在這種情況下,1和2

+0

創建JSON相當於強類型的類,並且只使用'JSON.Net'反序列化。訪問www.json2csharp.com以生成您的實體。 –

+1

@Amit - 他說他不能創建具體的類,鏈接也被破壞 - 你不需要www! –

回答

2

我會建議使用JSON.NET庫(通過的NuGet可用)。一旦你在你的項目中添加引用它,並導入庫類,您可以通過JSON結構這樣的穿越:

Dim jsonString = "{""items"":{""1"":[{""text"":""Man"",""itemID"":""1"",""checked"":1,""sequence"":1,""matchingtext"":"""",""weight"":0},{""text"":""goat"",""itemID"":""2"",""checked"":0,""sequence"":2,""matchingtext"":"""",""weight"":0},{""text"":""dog"",""itemID"":""3"",""checked"":0,""sequence"":3,""matchingtext"":"""",""weight"":0}],""2"":[{""text"":""pizza"",""itemID"":""1"",""checked"":1,""sequence"":1,""matchingtext"":"""",""weight"":0},{""text"":""horse"",""itemID"":""2"",""checked"":0,""sequence"":2,""matchingtext"":"""",""weight"":0},{""text"":""paper"",""itemID"":""3"",""checked"":0,""sequence"":3,""matchingtext"":"""",""weight"":0}]},""wbmode"":""dd"",""wbanswertype"":""sc""}" 

    Dim j As JObject = JObject.Parse(jsonString) 

    For Each item As JProperty In j.Item("items") 
     Dim itemObjects As JToken = item.Value 
     For Each i As JObject In itemObjects 
      For Each p In i 
       Debug.Print(p.Key.ToString & " = " & p.Value.ToString) 
      Next 
     Next 
    Next 
+0

完美我的朋友..我會嘗試JSON.NET和你的代碼.. –