Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - Deserialize binance API in json

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...