java - JSON Processing using Jackson 2.2 -
i using jackson 2.2 read large json string java object. using objectmapper
, read memory , transform json string object. happening in memory, entire json string loaded memory , transformed object.
if there more memory efficient way of doing it? i.e. without loading entire json string memory, should still able load object.
yes, typically use so-called "streaming" api iterate on json tokens; , once positioned on first token of value want (start_object json objects), use data-binding api, passing reader/parser use. details of depend on library. know @ least following support mode of operation:
- jackson
- gson
- genson
for jackson, basic streaming api usage talked here (for example); 1 thing not show how bind objects once positioned @ right place. assuming json like:
{ "comment" : "...", "values" : [ { ... value object 1 ... }, { ... value object 2. ... } ] }
you do:
objectmapper mapper = new objectmapper(); jsonparser jp = mapper.getfactory().createjsonparser(jsoninput); jp.nexttoken(); // return start_object, may want verify while (jp.nextvalue() != null) { // 'nextvalue' skips field_name token, if string fieldname = jp.getcurrentname(); if ("values".equals(fieldname)) { // yes, should point start_array while (jp.nexttoken() == jsontoken.start_object) { valueobject v = mapper.readvalue(jp, valueobject.class); // process individual value in whatever way want to... } } else if ("comment".equals(fieldname)) { // handle comment? } // may use else catch unknown fields, if } jp.close();
and should let bind 1 object @ time.
Comments
Post a Comment