2013-12-07 30 views
3

我想解析使用動態對象的JSON。這裏是圖書館,JSON數據轉換器,我使用:https://github.com/cmcdonaldca/shopify.net解析動態數據

這是我的錯誤信息:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:「串」不 不包含定義'產品'

這裏是我的JSON:

http://pastebin.com/pnmz7jN0

這裏是我的代碼:

public void GetProducts() 
    { 
     // The JSON Data Translator will automatically decode the JSON for you 
     dynamic data = _api.Get("/admin/products.json"); 

     // the dynamic object will have all the fields just like in the API Docs 
     foreach (var product in data.products) 
     { 
      Console.Write(product.title); 
     } 
    } 

我試圖data.products和數據,但我不能讓裏面的產品對象。

+0

向我們展示這個 「JSON數據轉換器」 的實施。 –

+0

json對象是否有標題屬性? – PCG

+0

我添加了代碼,是的,有一個標題屬性。 –

回答

0

考慮data[0].title作爲開始,但在調試模式下,您應該能夠瀏覽對象,或使用立即窗口並運行一些手動查詢。

關於錯誤,您的dynamic data可能只是一個字符串對象,試試你自己的代碼只是刪除單詞「產品」。

public void GetProducts() 
{ 
    // The JSON Data Translator will automatically decode the JSON for you 
    dynamic data = _api.Get("/admin/products.json"); 

    // the dynamic object will have all the fields just like in the API Docs 
    foreach (var product in data) //here is the change from the code you posted 
    { 
     Console.Write(product.title); 
    } 
} 

Your sample data parsed

+0

在這種情況下,從data.products到data的變化如何解決? – Khez

+0

因爲動態數據可能已經是一個數組了,如果你做data.products,這意味着你引用了稱爲數據的動態對象和它的屬性「products」。 JSON符號具有名稱的事實並不意味着您使用的任何API將使用名稱反序列化它。再看看圖片,動態對象數據可能是一個數組,因此而不是foreach(p in data.products)嘗試foreach(p in data) –

+0

順便說一句,我的例子是「幹嘗試」。我沒有在運行時測試這個方法。無法測試它我不確定即使提到了JSON數據轉換器,「_api」指的是什麼,換句話說,我太懶了:) –