Есть некий внешний сервис, отдающий такой объект:
{
"timestamp": час
"asks": масив ордерів на продаж
[
[ціна, об'єм]
],
"bids": масив ордерів на покупку
[
[ціна, об'єм]
]
}
Я реализовал его и сериализую с помощью Newtonsoft пакета так:
public class Depth
{
[JsonProperty(PropertyName = "timestamp")]
public int timestamp;
[JsonProperty(PropertyName = "asks")]
public Dictionary<string, string> asks;
[JsonProperty(PropertyName = "bids")]
public Dictionary<string, string> bids;
}
и соответственно место где я получаю данный объект из http запроса и десеарилизую
var json = await response.Content.ReadAsStringAsync();
var d = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(json));
В итоге ошибка -->
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' 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."
Возможно для Dictionary имеется какоето другое [сво-во] сериализации или же я неправильно десеарилизую?
Пробовал вмесо Dictionary в классе поля через List<KeyValuePair<string,string>> делать, но тогда значения KeyValuePair равны null.
Окей, допустим у нас есть json
string json = @"{
""timestamp"": 1530724151,
""asks"": [
[""300943.0"", ""0.000299""],
[""300850.0"", ""0.004703""],
[""300500.0"", ""0.056""],
[""300000.0"", ""0.593274""],
[""299900.0"", ""0.0342""],
[""299500.0"", ""0.003196""]
],
""bids"": [
[""300943.0"", ""0.000299""],
[""300850.0"", ""0.004703""],
[""300500.0"", ""0.056""],
[""300000.0"", ""0.593274""],
[""299900.0"", ""0.0342""],
[""299500.0"", ""0.003196""]
]
}";
И мы создали такие классы, которые нам очень нравятся
public class Depth
{
public int timestamp;
public MyPair[] asks;
public MyPair[] bids;
}
public class MyPair
{
public decimal Cost{get;set;}
public decimal Volume{get;set;}
}
И теперь мы хотим сконвертировать наш json в наши классы. Но вот незадача - в jsone то поля выглядят как массив массивов, а нам надо массив наших объектов. Что тут можно сделать? А давайте напишем наш конвертер
private class MyAwesomeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyPair);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);
return new MyPair
{
Cost = array[0].Value<decimal>(),
Volume= array[1].Value<decimal>()
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Этот конвертер будет работать только когда надо будет распарсить конкретно наш класс MyPair, для остальных классов будет работать встроенный конвертер. Как теперь все собрать вместе? Вот так:
var depth = JsonConvert.DeserializeObject<Depth>(json, new MyAwesomeConverter());
Все, никаких спец объектов больше создавать не нужно.
Все довольно просто:
public class Depth
{
[JsonProperty("timestamp")]
public int Timestamp;
[JsonProperty("asks")]
public List<Quote> Asks;
[JsonProperty("bids")]
public List<Quote> Bids;
}
public class Quote : List<decimal>
{
public decimal Price => Count > 0 ? this[0] : -1;
public decimal Volume => Count > 1 ? this[1] : -1;
}
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости