c# - Parse json file without key values -
i'm trying parse json file json.net
. content of json file is:
[ [ "240521000", "37.46272", "25.32613", "0", "71", "90", "15", "2016-07-18t21:09:00" ], [ "237485000", "37.50118", "25.23968", "177", "211", "273", "8", "2015-09-18t21:08:00" ] ]
i created following code:
webclient wc = new webclient(); string json = wc.downloadstring("data.json"); dynamic myobject = jsonconvert.deserializeobject<dynamic>(json); foreach (string item in myobject[0]) { var x = item[0]; }
how can loop through individual items without having key?
while diin_'s answer answers question, don't think it's solution. having had @ marine traffic api, feels they've made poor json implementation, xml representation has attribute names values. json should've been:
{"positions": ["position": {"mmsi": "311029000", "lat": "37.48617", "long": "24.37233", ...}]}
because isn't, have json string instead it's nested array, array two-dimensional array, , you'd have hope data model isn't changed remove something, you'd have use index retrieve data.
however, if @ xml available api, attributes have names. suggest instead download xml, , parse object - model, in asp.net - typed, , can used more in view.
here's example i've got running. uses xml parsing first read xml api, , parse json, , actual object.
first, model class (position.cs)
public sealed class position { [jsonproperty("@mmsi")] public string mmsi { get; set; } [jsonproperty("@lat")] public string latitude { get; set; } [jsonproperty("@lon")] public string longitude { get; set; } [jsonproperty("@speed")] public string speed { get; set; } [jsonproperty("@heading")] public string heading { get; set; } [jsonproperty("@course")] public string course { get; set; } [jsonproperty("@status")] public string status { get; set; } [jsonproperty("@timestamp")] public string timestamp { get; set; } }
next, parsing logic:
var client = new webclient(); var xml = client.downloadstring("data.xml"); var doc = new xmldocument(); doc.loadxml(xml); var json = jsonconvert.serializexmlnode(doc); var positions = jobject.parse(json).selecttoken("pos").selecttoken("row").toobject<list<position>>();
at end of parsing logic, have list of positions can pass view, , have typed.
as brief example:
// after have positions list return view(positions);
positions.cshtml
@model list<positions> <h2>positions</h2> @foreach (var position in model) { <p>@position.mmsi (@position.latitude, @position.longitude)</p> }
i hope useful you. if have questions, drop me comment.
Comments
Post a Comment