簡體   English   中英

C#反序列化嵌套的JSON

[英]c# Deserialize Nested json

我是使用json的新手-我正在使用現有的json數據結構並嘗試輸出數據,但是現有數據結構的一部分讓我感到困惑。

以下是我的json數據:

{"supplier":
    {
    "supplierid":3590,
    "code":"ENCLES",
    "name":"Les Miserables",
    "analyses":[],
    "amenities":[],
    "info":
        "{\"Supplier\":
            {
            \"Name\":\"Les Miserables\",
            \"LastUpdate\":\"2011-11-01T22:16:06Z\",
            \"Address3\":\"London\",
            \"Address2\":\"51 Shaftesbury Avenue\",
            \"PostCode\":\"W1D 6BA\",
            \"Address1\":\"Queen's Theatre\",
            \"Address4\":\"\",
            \"Address5\":\"\",
            \"SupplierId\":3590,
            \"SupplierCode\":\"ENCLES\"
            }
        }",
        ...
        }

讓我感到難過的是信息數據-這是另一個嵌套的json字符串。

我的課是:

public class TheatreListing
{
    public supplier supplier;
}

public class supplier
{
    public int? supplierid { get; set; }
    public string code { get; set; }
    public string name { get; set; }
    public listingInfo info { get; set; }
}


public class listingInfo
{
    public Address Supplier { get; set; }

}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string Address4 { get; set; }
    public string Address5 { get; set; }
    public string PostCode { get; set; }
}

我嘗試訪問數據的代碼是:

TheatreListing tl = Json.Decode<TheatreListing>(json);
StringBuilder sbb = new StringBuilder();
sbb.Append("Name = " + tl.supplier.name.ToString());
sbb.Append("<br />Supplier ID = " + tl.supplier.supplierid.ToString());
sbb.Append("<br />Code = " + tl.supplier.code.ToString());
sbb.Append("<br />Address = " + tl.supplier.info.Supplier.Address2.ToString());
litOutput.Text += sbb.ToString();

我收到的錯誤消息是:

Cannot convert object of type 'System.String' to type 'listingInfo'

有人可以指導我這里的錯誤嗎?

干杯

奈傑爾

我建議您看幾件事:

1)使用json2csharp從現有的json生成c#類

2)使用json.net反序列化您的json,就像冠軍!

問題出在線內

TheatreListing tl = Json.Decode<TheatreListing>(json);

我認為您當前的json轉換為TheatreListing失敗。

您為什么不嘗試使用JavascriptSerializer,看看它是否有效。

JavaScriptSerializer js = new JavaScriptSerializer();
TheatreListing  tree = js.Deserialize <TheatreListing>(json);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM