Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex json deserialization

Tags:

json

c#

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.


2 Answers

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

like image 52
Satpal Avatar answered Dec 08 '25 17:12

Satpal


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.