user238801
user238801

Reputation:

Complex json deserialization

I have to deserialize the following json response (the Result list has variable length):

{
    "ResultSet": {
        "Query": "volkswagen",
        "Result": [
            {
                "symbol": "VLKAY",
                "name": "Volkswagen AG",
                "exch": "PNK",
                "type": "S",
                "exchDisp": "OTC Markets",
                "typeDisp": "Equity"
            },
            {
                "symbol": "VOW3.DE",
                "name": "Volkswagen AG",
                "exch": "GER",
                "type": "S",
                "exchDisp": "XETRA",
                "typeDisp": "Equity"
            },
            {
                "symbol": "VOW.DE",
                "name": "Volkswagen AG",
                "exch": "GER",
                "type": "S",
                "exchDisp": "XETRA",
                "typeDisp": "Equity"
            }
        ]
    }
}

What I got:

JavaScriptSerializer js = new JavaScriptSerializer();
string jsonString = "...String is here...";
SearchObj obj = js.Deserialize<SearchObj>(jsonString);

I understand that I usually have to create a fitting obj. e.g. SearchObj which will get filled but in this case I'm not entirely sure how this object is supposed to look like. I came up with:

class Data 
{
    public string symbol { get; set; }
    public string name { get; set; }
    public string exch { get; set; }
    public string type { get; set; }
    public string exchDisp { get; set; }
    public string typeDisp { get; set; }
}

class Container 
{
    public string Query { get; set; }
    public List<Data> Result { get; set; }
}

class SearchObj
{
    public Container ResultSet { get; set; }
}

But guess what, it's not working, I only get ResultSet = null.

Upvotes: 3

Views: 520

Answers (3)

Philippe Maes
Philippe Maes

Reputation: 510

You can use http://www.json2charp.com to create your classes.

Upvotes: 0

user238801
user238801

Reputation:

I always feel bad when I answer my own question but here it goes.

Basically my idea was correct, I only made one mistake which is that I don't need the

class SearchObj
{
    public Container ResultSet { get; set; }
}

Using

Container obj = js.Deserialize<Container>(jsonString);

instead of

SearchObj obj = js.Deserialize<SearchObj>(jsonString);

made the trick. Both Data[] and List<Data> in Container work btw.

Edit: From giammins comment it seems that it is working on some machines without that change but I guess that's a case for undefined behavior.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

Try to change your class Container as

 class Container 
 {
     public string Query { get; set; }
     public Data[] Result { get; set; }
 } 

I have not tested it, based on my observation

Upvotes: 1

Related Questions