Nigel Wilson
Nigel Wilson

Reputation: 1

c# Deserialize Nested json

I am new to working with json - I am working with an existing json data structure and trying to output the data, however part of the existing data structure has me stumped.

The following is my json data:

{"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\"
            }
        }",
        ...
        }

The bit that has me stumped is the info data - it is another nested json string.

My class is:

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; }
}

My code to try and access the data is:

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();

The error message I am getting is:

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

Can anyone please guide me on the error of my ways here ?

Cheers

Nigel

Upvotes: 0

Views: 2216

Answers (2)

Rob Lauer
Rob Lauer

Reputation: 3171

I recommend looking at a couple of things:

1) Use json2csharp to generate your c# classes from your existing json

2) Use json.net to deserialize your json, works like a champ!

Upvotes: 3

abhishek
abhishek

Reputation: 2992

The problem is inside the line

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

I think the conversion to TheatreListing is failed for your current json.

Why dont you try using JavascriptSerializer and see whether it works or not.

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

Upvotes: 0

Related Questions