Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to Deserialize data from binance API. The format in the website is:

{
  "lastUpdateId": 82930322,
  "bids": [
    ["0.09766700","12.64700000",[]],
    ["0.09766600","0.19500000",[]],
    ["0.09765800","0.30300000",[]],
    ["0.09765600","3.50000000",[]],
    ["0.09765500","0.14900000",[]]
  ],

I try to save the data to:

public string NameOfCoin { get; set; }
public string[][]  bids { get; set; }

And I get exception that it can't read the [] in the end of the array. I tryed also for a diffrent format like float or string withour array and it dosent work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, the simplest solution is to change the type of your bids property from string[][] to object[][]. That will allow the deserialization to succeed, but working with the bids array will be awkward. You will have to do type checking on the items and cast them appropriately when you use them.

A better idea is to filter out the unwanted empty array values during deserialization. You can do that with a custom JsonConverter (assuming you are using Json.Net -- your question did not indicate what JSON serializer you are using). Here is one that should do the job:

class CustomConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray rows = JArray.Load(reader);
        foreach (JArray row in rows.Children<JArray>())
        {
            foreach (JToken item in row.Children().ToList())
            {
                if (item.Type != JTokenType.String)
                    item.Remove();
            }
        }
        return rows.ToObject<string[][]>(serializer);
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return false;
    }
}

To use the converter, mark the bids property in your class with a [JsonConverter] attribute like this:

[JsonConverter(typeof(CustomConverter))]
public string[][] bids { get; set; }

Then you can deserialize to your class as usual and it should "just work".

Working demo: https://dotnetfiddle.net/TajQt4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...