2012-04-01 170 views
0

我是新来的使用json - 我正在使用现有的json数据结构并尝试输出数据,但现有数据结构的一部分让我难住。c#反序列化嵌套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' 

谁能请在这里指导我的方式错误?

干杯

奈杰尔

+0

我会建议反序列化内部的东西到一个“串”,然后反序列化,在第二遍传递给正确的类型。它可能会注册一个自定义类型的转换器,但是...(理想情况下,它不会嵌套在这样一个丑陋的方式: - /) – 2012-04-01 23:28:19

+0

对不起,应该“info”:“{\”Supplier \ “:...不是”信息“:{\”供应商\“:(无先前引用的大括号)以及结束大括号的相同事情? – mho 2012-04-02 02:13:46

回答

0

的问题是线

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

我想转换为TheatreListing失败您当前的JSON内。

为什么不尝试使用JavascriptSerializer并查看它是否有效。

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

我建议在看一两件事情:

1)使用json2csharp从现有的JSON

2)使用json.net到反序列化JSON生成的C#类,就像一个冠军!