Reading value of nested key in JSON with Java (Jackson) -
i'm new java programmer coming background in python. have weather data that's being collected/returned json nested keys in it, , don't understand how pull values out in situation. i'm sure question has been asked before, swear i've googled great deal , can't seem find answer. right i'm using json-simple, tried switching jackson , still couldn't figure out how this. since jackson/gson seem used libraries, i'd love see example using 1 of libraries. below sample of data, followed code i've written far.
{ "response": { "features": { "history": 1 } }, "history": { "date": { "pretty": "april 13, 2010", "year": "2010", "mon": "04", "mday": "13", "hour": "12", "min": "00", "tzname": "america/los_angeles" }, ... } } main function
public class tester { public static void main(string args[]) throws malformedurlexception, ioexception, parseexception { wundergroundapi wu = new wundergroundapi("*******60fedd095"); jsonobject json = wu.historical("san_francisco", "ca", "20100413"); system.out.println(json.tostring()); system.out.println(); //this returns 1 level. further .get() calls throw exception system.out.println(json.get("history")); } } the function 'historical' calls function returns jsonobject
public static jsonobject readjsonfromurl(url url) throws malformedurlexception, ioexception, parseexception { inputstream inputstream = url.openstream(); try { jsonparser parser = new jsonparser(); bufferedreader buffreader = new bufferedreader(new inputstreamreader(inputstream, charset.forname("utf-8"))); string jsontext = readall(buffreader); jsonobject json = (jsonobject) parser.parse(jsontext); return json; } { inputstream.close(); } }
with jackson's tree model (jsonnode), have both "literal" accessor methods ('get'), returns null missing value, , "safe" accessors ('path'), allow traverse "missing" nodes. so, example:
jsonnode root = mapper.readtree(inputsource); int h = root.path("response").path("history").getvalueasint(); which return value @ given path, or, if path missing, 0 (default value)
but more conveniently, can use json pointer expression:
int h = root.at("/response/history").getvalueasint(); there other ways too, , more convenient model structure plain old java object (pojo). content fit like:
public class wrapper { public response response; } public class response { public map<string,integer> features; // or maybe map<string,object> public list<historyitem> history; } public class historyitem { public mydate date; // or map<string,string> // ... , forth } and if so, traverse resulting objects java objects.
Comments
Post a Comment