c# - How do I deserialize json so that some json properties gets assigned to an array or List? -
using json.net, how deserialize following json orderdepthfeed class provided below? want bid1 go bid[0], bid2 bid[1] , on.
{ "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 { 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; } }
here's code use, , pascalcasecontractresolver changes case , removes underscores in property names overriding resolvepropertyname();
var serializersettings = new jsonserializersettings(); serializersettings.contractresolver = new pascalcasecontractresolver(); var orders = jsonconvert.deserializeobject<orderdepthfeed>(json, serializersettings);
here custom converter:
public class jsonorderdepthfeedconverter : jsonconverter { public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { //implement if want convert json in 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 { = 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]; (var = 1; <= 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; } }
and how use it:
var settings = new jsonserializersettings { converters = { new jsonorderdepthfeedconverter() } }; var order = jsonconvert.deserializeobject<orderdepthfeed>(json, settings);
Comments
Post a Comment