java - Parse list of complex JSON objects using Jackson -
i have list of json objects like:
[ { "id": "a", "objs": [ { "obj1": 1 }, { "obj2": 0 }, ] }, { "id": "a", "objs": [ { "obj1": 1 }, { "obj2": 0 }, ] } ]
and load them list of myobj:
class myobj { private final string id; private final hashmap<string, integer> objs; // constructors, etc. here... } arraylist<myobj> list;
is there smart way using jackson objectmapper or other bindings; i.e., minimal boilerplate code? without hashmap simple matter of:
list = mapper.readvalue(file, new typereference<arraylist<myobj>>() {});
but hashmap pretty seems kill that. ideas?
first of need model class json. should write own parser reading data array (map, list, etc.). jackson.
small example old project.
model class:
package ru.model; import javax.persistence.*; import java.io.serializable; import java.io.unsupportedencodingexception; import java.text.parseexception; import java.text.simpledateformat; import java.util.date; import java.util.locale; public class entry implements serializable { private static final long serialversionid = 8201337883209943936l; private integer primary_id; private integer id; private string description; private integer votes; private string author; private date date; private string gifurl; private string previewurl; private string embedid; private string type; // getters , setters }
example of parser:
public static list<entry> getallentries(string jsonstring) { list<entry> entries = new arraylist<entry>(); try { if (jsonstring.length() == 0) { throw new exception("empty json!"); } } catch (exception e) { e.printstacktrace(); } objectmapper objectmapper = new objectmapper(); try { jsonnode rootnode = objectmapper.readtree(jsonstring); jsonnode resultnode = rootnode.findpath("result"); // choose concrete element in json array if (resultnode.size() > 0) { (int = 0; < resultnode.size(); i++) { entries.add(objectmapper.readvalue(resultnode.get(i).tostring(), entry.class)); } } } catch (ioexception e) { e.printstacktrace(); } return entries; }
example of json:
{"result": [ {"id":94, "description":"description111", "votes":1, "author":"sashvd", "date":"mar 15, 2013 4:09:03 pm", "gifurl":"http://-..", "previewurl":"http://.."} ], "totalcount":88} }
Comments
Post a Comment