gorrch
gorrch

Reputation: 551

Can not deserialize JSON with array in array

How I should deserialize below JSON?

{
    "lastUpdateId": 131537317,
    "bids": [
        ["0.08400000", "0.54300000", []],
        ["0.08399800", "0.70800000", []],
        ["0.08399400", "1.22700000", []],
        ["0.08399300", "0.61700000", []],
        ["0.08399100", "0.35400000", []]
    ],
    "asks": [
        ["0.08408300", "0.09100000", []],
        ["0.08408400", "5.55300000", []],
        ["0.08408600", "0.71800000", []],
        ["0.08408900", "0.14500000", []],
        ["0.08409000", "0.15100000", []]
    ]
}

I use classes like below. Ask and Bid are the same.

Order deserializedProduct = JsonConvert.DeserializeObject<Order>(timeServer);

public class Order
{
    public int lastUpdateId { get; set; }

    public List<Bid> bids { get; set; }

    public List<Ask> asks { get; set; }
}

public class Bid
{
    public List<string> Items { get; set; }
}

I have error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WebApplication2.Models.Bid' 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 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. Path 'bids[0]', line 1, position 35.

Upvotes: 1

Views: 1902

Answers (1)

FaizanHussainRabbani
FaizanHussainRabbani

Reputation: 3439

Better class to represent your JSON is:

public class Order
{
    public int lastUpdateId { get; set; }
    public List<List<object>> bids { get; set; }
    public List<List<object>> asks { get; set; }
}

As @maccettura mentioned in his comment Bids and Asks are IEnumerable<IEnumerable<string>>

enter image description here

Upvotes: 1

Related Questions