使用Json。Net,我如何将以下json反序列化到下面提供的OrderDepthFeed类?我想让bid1进入Bid[0], bid2进入Bid[1],以此类推。
{
"i": "101",
"m": 11,
"tick_timestamp": 1440479701986,
"bid1": 78.00,
"bid_volume1": 60,
"bid_orders1": 1,
"ask1": 80.50,
"ask_volume1": 500,
"ask_orders1": 1,
"bid2": 77.50,
"bid_volume2": 500,
"bid_orders2": 1,
"ask2": 82.00,
"ask_volume2": 1560,
"ask_orders2": 2,
"bid3": 77.00,
"bid_volume3": 107,
"bid_orders3": 2,
"ask3": 82.95,
"ask_volume3": 75,
"ask_orders3": 1,
"bid4": 76.30,
"bid_volume4": 200,
"bid_orders4": 1,
"ask4": 83.40,
"ask_volume4": 49,
"ask_orders4": 1,
"bid5": 76.00,
"bid_volume5": 506,
"bid_orders5": 2,
"ask5": 83.50,
"ask_volume5": 1500,
"ask_orders5": 1
}
,
public class OrderDepthFeed {
public int I { get; set; }
public int M { get; set; }
public int TickTimestamp { get; set; }
public double?[] Ask { get; set; }
public int?[] AskVolume { get; set; }
public double?[] Bid { get; set; }
public int?[] BidVolume { get; set; }
}
下面是我使用的代码,PascalCaseContractResolver通过重写ResolvePropertyName();
仅更改大小写并删除属性名称中的下划线var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new PascalCaseContractResolver();
var orders = JsonConvert.DeserializeObject<OrderDepthFeed>(json, serializerSettings);
下面是一个自定义转换器:
public class JsonOrderDepthFeedConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
//implement this if you want to convert to json in the same way
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var order = JObject.Load(reader);
var orderDepthFeed = new OrderDepthFeed
{
I = order["i"].Value<int>(),
M = order["m"].Value<int>(),
TickTimestamp = order["tick_timestamp"].Value<long>()
};
const int count = 5;
orderDepthFeed.Ask = new double?[count];
orderDepthFeed.AskVolume = new int?[count];
orderDepthFeed.Bid = new double?[count];
orderDepthFeed.BidVolume = new int?[count];
for (var i = 1; i <= count; i++)
{
JToken aux;
if (order.TryGetValue("ask" + i, out aux)) orderDepthFeed.Ask[i - 1] = aux.Value<double>();
if (order.TryGetValue("ask_volume" + i, out aux)) orderDepthFeed.AskVolume[i - 1] = aux.Value<int>();
if (order.TryGetValue("bid" + i, out aux)) orderDepthFeed.Bid[i - 1] = aux.Value<double>();
if (order.TryGetValue("bid_volume" + i, out aux)) orderDepthFeed.BidVolume[i - 1] = aux.Value<int>();
}
return orderDepthFeed;
}
public override bool CanConvert(Type objectType)
{
return typeof(OrderDepthFeed) == objectType;
}
}
和如何使用:
var settings = new JsonSerializerSettings { Converters = { new JsonOrderDepthFeedConverter() } };
var order = JsonConvert.DeserializeObject<OrderDepthFeed>(json, settings);
编写自己的JsonConverter
,以便完全控制(反)序列化。创建一个从JsonConverter
派生的类,并覆盖以下方法:CanConvert
, ReadJson
和WriteJson