2014-09-05 39 views
1

我很難迭代一個簡單的JSON。我用Javascript很容易做到,但無法在C#中使用json.net。 這是我的JSON:從一個特定的鍵迭代json

{ 
    "term0":{ 
     "id":"2131sd0", 
     "senses":{ 
     "0":{ 
      "synonyms":{ 
       "0":{ 
        "synonym":"that", 
        "context":"" 
       }, 
       "1":{ 
        "synonym":"the indicated", 
        "context":"" 
       }, 
       "2":{ 
        "synonym":"the present", 
        "context":"" 
       }, 
       "3":{ 
        "synonym":"aforementioned", 
        "context":"" 
       } 
      } 
     } 
     } 
    }, 
    "term1":{ 
     "id":"2131sd1", 
     "senses":{ 
     "0":{ 
      "synonyms":{ 
       "0":{ 
        "synonym":"the one", 
        "context":"" 
       }, 
       "1":{ 
        "synonym":"this one", 
        "context":"" 
       }, 
       "2":{ 
        "synonym":"the one in question", 
        "context":"" 
       } 
      } 
     } 
     } 
    } 
} 

這是我的C#:

JObject rootObject = JObject.Parse(jsonText); 
foreach(dynamic a in rootObject.SelectToken("term0")["senses"]["0"]["synonyms"]) 
{ 
    Debug.WriteLine(a["synonym"]); 
} 

其崩潰。我錯過了什麼?

謝謝。

錯誤:

A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll Additional information: Cannot dynamically invoke method 'WriteLine' because it has a Conditional attribute

+1

'這是碰撞'碰撞什麼?你會得到什麼錯誤信息?把它放在你的問題。 – 2014-09-05 17:15:00

+0

當我嘗試它,我得到一個'InvalidOperationException'與消息:'不能訪問Newtonsoft.Json.Linq.JProperty上的子值。' – 2014-09-05 17:25:27

+2

@MattBurland我也是這樣的馬特。你必須調用'a.First [「同義詞']',然後你會收到他描述的異常。 – 2014-09-05 17:28:00

回答

3

它是動態的,因此我們將它轉​​換爲一個對象,然後調用ToString()方法。例如:

Debug.WriteLine(((object)a.First["synonym"]).ToString()); 
+0

我收到「無法訪問Newtonsoft.Json.Linq.JProperty上的子值」。錯誤 – Cornwell 2014-09-05 17:30:09

+2

由於@ByteBlast指出,它應該是'Debug.WriteLine(((object)a.First [「synonym」])。ToString());' – 2014-09-05 17:31:35

+0

@MattBurland好的,謝謝。我想我應該實際測試它。 – Donal 2014-09-05 17:32:43