Tuesday, 15 March 2011

C# Getting unnamed list from json web api using JSON.NET -



C# Getting unnamed list from json web api using JSON.NET -

i'm using json.net info several web apis, explained me in previous q&a. i've stumbled upon kind of web api can't parse because don't know how to. one: https://data.bter.com/api/1/tickers

as can see, it's json collection of trading pairs. collection unnamed, i'd have create class each trading pair, isn't dynamic. i'm using next parse url:

public static t downloadserializedapi<t>(string address) t : new() { t newt = new t(); httpclient client = new httpclient(); using (stream s = client.getstreamasync(address).result) using (streamreader sr = new streamreader(s)) using (jsonreader reader = new jsontextreader(sr)) { jsonserializer serializer = new jsonserializer(); newt = serializer.deserialize<t>(reader); } homecoming newt; }

now i'd set t class "tradingpairs" in there list tradingpairs. way see now, long list of hardcoded pairs :(

anyone care help me? ;)

this json little tricky because of changing property names, should still able utilize generic method data.

i think approach take create class represent trading pair , utilize [jsonextensiondata] feature work around fact vol_xxx property names alter each pair. deserialize dictionary<string, tradingpair>.

here's how define class:

public class tradingpair { public string result { get; set; } public decimal lastly { get; set; } public decimal high { get; set; } public decimal low { get; set; } public decimal avg { get; set; } public decimal sell { get; set; } public decimal purchase { get; set; } [jsonextensiondata] private dictionary<string, object> vols { get; set; } }

then deserialize info this:

var tradingpairs = downloadserializedapi<dictionary<string, tradingpair>>(url);

c# json json.net web-api

No comments:

Post a Comment