nighthawk
nighthawk

Reputation: 832

Deserialize JSON data from JSON array

This question is probably asked a dozen times but i can't find anything useful so...

JSON data looks like this

{
"aaData": [
        [
        8120,
        "username",
        "[email protected]",
        "\/",
        "CUSTOMER ( SellerName )",
        "name",
        "<span class=\"label label-danger\">2015-08-05<\/span>",
        "<a class=\"btn btn-xs btn-primary manageDevices\" href=\"#\" id=\"manageDevices\" data-customerid=\"8120\" data-toggle=\"modal\">1<\/a>",
        "<a id=\"8120\" href=\"http:\/\/cms.*********.com:8081\/manageCustomers?customerId=8120\" class=\"btn btn-xs btn-primary\">View<\/a>",
        "YES"
         ],
         ....
         ]
     ],
    "sEcho": "NULL",
    "iTotalRecords": 65,
    "iTotalDisplayRecords": 65
}

Obviously, this fails:

private class OuterUser
{
    string id { get; set; }
    string username { get; set; }
    string line { get; set; }
    string reseller { get; set; }
    string username2 { get; set; }
    string date1 { get; set; }
    string manage { get; set; }
    string manageUser { get; set; }
    string active { get; set; }
}

dynamic jsonDe = JsonConvert.DeserializeObject<OuterUser>(rpl);
//dynamic j = JsonConvert.DeserializeObject<List<OuterUser>>(rpl);

Anyone has idea how to deserialize this? And explain what i did wrong. I don't need data on bottom (total records) and so on. Actually, only thing that i need is ID on beginning, username and email. Commented code also fails and i think that is part of solution.

Upvotes: 0

Views: 176

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

If you clean up your JSON (remove ....]) and post it to Json2Csharp.com, you'll get:

public class RootObject
{
    public List<List<object>> aaData { get; set; }
    public string sEcho { get; set; }
    public int iTotalRecords { get; set; }
    public int iTotalDisplayRecords { get; set; }
}

As the list of values you're interested in seems to be a nested array of various types. That can't be mapped to your OuterUser class, as the values aren't in key: value notation, they're just array elements.

So you'll have to deserialize to RootObject, then step into (or iterate over) the List<List<object>>:

var parsed = JsonConvert.DeserializeObject<RootObject>(rpl);
var firstUser = parsed.aaData[0]; 
var firstUserID = firstUser[0]; // 8120

Upvotes: 5

Related Questions