1

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.

maccettura
  • 10,514
  • 3
  • 28
  • 35
gorrch
  • 521
  • 3
  • 16
  • 2
    Where is `Items` supposed to magically come from? There is no `Items` in the JSON. Re-read the message, it's very clear. You'll need an array (it'll have to be `object`, since the entries are either strings or empty arrays [bizarrely]) or a list, not `Bid`. – T.J. Crowder Feb 26 '18 at 23:06
  • 1
    past your jason on http://json2csharp.com/ to get classes – Leszek P Feb 26 '18 at 23:06
  • Looks like issue with Bid, as it should have just List whereas value has something different. – PM. Feb 26 '18 at 23:06
  • @LeszekRepie that tool isnt very useful anymore. Visual Studio has this built in since 2015 – maccettura Feb 26 '18 at 23:08
  • See https://stackoverflow.com/questions/48251048/deserialize-binance-api-in-json or https://stackoverflow.com/questions/47879889/json-net-converting-array-of-arrays-with-different-types – dbc Feb 26 '18 at 23:29

1 Answers1

1

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

FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46