0

How can I deserialize the following JSON into a custom object using C# and Json.NET:

[ {
    'data': [
        [ '100473','3481282801.0' ],
        [ '100472','3481275600.0' ],
        [ '100471','3481273800.0' ],
        [ '100470','3481263900.0' ],
        [ '100469','3481263000.0' ]
    ],
    'error': '',
    'statement_time': 0.00440700000000000030,
    'total_time': 0.00475200000000000010
} ]

It is an array containing a single object. To make things more interesting the object contains an array of arrays. (I have no control over the format, unfortunately.) I am relatively new to JSON and thought I'd try Json.NET. I am open to other JSON frameworks if it would make things easier.

2 Answers 2

4

Using Json.Net

var result = JsonConvert.DeserializeObject<List<MyObject>>(str);

public class MyObject
{
    public List<List<string>> data { get; set; }
    public string error { get; set; }
    public double statement_time { get; set; }
    public double total_time { get; set; }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is what I had tried at first but it gives me the following error message: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Target' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
I programmatically removed the square brackets from the beginning and end (the outer array) before attempting to deserialize the object. It's working now but is this the best way to do it? I don't know why the system I'm querying returns the object in an array. I don't see any advantage to this format.
@Ryan Given your json in question, above code runs perfectly. (I tested it again before writing this comment)
You're right. I was attempting to deserialize to a single object instead of a list of objects. Once I changed that it worked without having to remove the brackets.
0

If you're using C# 4.0 or higher, use dynamic object:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access members of JSON using dot notation like this:

string s = json[0].data[0][0][1];

This, for example, will return you number 100473.

1 Comment

I know, it should just illustrate that using this way you'll get this number out from the JSON object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.