c# - Deserialise JSON and access content using Linq to JSon -
i have following json stored in cookie wish parse:
{"package":[{"id":"5054","nodeid":"3286"},{"id":"8888","nodeid":"7777"}], "hotel":[{"id":"3421","nodeid":"1234"},{"id":"8748","nodeid":"2435"}], "activity":[{"id":"5054","nodeid":"3286"},{"id":"8888","nodeid":"7777"},{"id":"2131","nodeid":"2342"}]}
i understand accepted answer on question deserializing json .net object using newtonsoft (or linq json maybe?) can use following code access individual objects within json notation:
jtoken token = jobject.parse(stringfullofjson); int page = (int)token.selecttoken("page"); int totalpages = (int)token.selecttoken("total_pages");
i've therefore adapted code follows:
httpcookie cookie = request.cookies.get("wishlist"); string jsonstring = string.empty; string nodeid = string.empty; if (cookie != null) { jsonstring = cookie.value; jtoken token = jobject.parse(jsonstring); }
i wish retreive package array example , loop through each of items in array , output ids in following format:
5054,8888
from example code sort of came following approach i'm not sure if i'm proceeding in right direction.
jobject obj = jobject.parse(jsonstring); jarray packages = (jarray)obj["package"];
what best way of specifying 1 of arrays eg. hotel, package , looping through contents , outputting each of id nodes found? nodeid numeric id string or int adds layer of complication.
any appreciated , apologise if sumwhat stupid or easy question have jsut started working .net , oo of concepts still bit foggy.
here's how this, i'd create classes required deserialize json :-
public class jsoncookie { public package[] package { get; set; } public hotel[] hotel { get; set; } public activity[] activity { get; set; } } public class package { public string id { get; set; } public string nodeid { get; set; } } public class hotel { public string id { get; set; } public string nodeid { get; set; } } public class activity { public string id { get; set; } public string nodeid { get; set; } }
now, create method deserialising :-
public jsoncookie getjsoncookieresponse() { try { // add own code gets response here. // string response = "{"package":[{"id":"5054","nodeid":"3286"},{"id":"8888","nodeid":"7777"}], "hotel":[{"id":"3421","nodeid":"1234"},{"id":"8748","nodeid":"2435"}], "activity":[{"id":"5054","nodeid":"3286"},{"id":"8888","nodeid":"7777"},{"id":"2131","nodeid":"2342"}]}"; //return new jsonserializer().deserialize<jsoncookie>(new jsontextreader(new stringreader(response))); } catch { return null; } }
from jsoncookie object returned, can use linq pick out need follows :-
x.package.select(p=>p.id);
Comments
Post a Comment