generic parsing of json to java objects -


i have java classes myclass1 , myclass2 state saved in json objects:

"myclass1":[{"var1":"value1","var2":"value2"},{"var1":"value3","var2":"value4"}] "myclass2":{"var11":"value5","var22":"value6"} 

now want write generic method parse json objects java objects using net.sf.json help.

let's start myclass1 - want create list<myclass1> containing 2 objects described in json.

1: public static <t> list<t> loadbesfromjson(final file jsoninputfile, final class<t> tclazz) throws ioexception { 2:    final list<t> result = new arraylist<t>();  3:    final jsonobject input = parsefiletojsonobject(jsoninputfile);  4:    if (input.containskey(tclazz.tostring())) { 5:       jsonarray arr = input.getjsonarray(tclazz.tostring()); //valid??? 6:       (int = 0; < arr.size(); i++) { 7:          jsonobject obj = arr.getjsonobject(i); 8:          //now, how create object of type t? 9:       } 10:   }  11:   return result; 12:} 

my first question - line 5 valid? second question in line 8: @ point want create object of type t, possible?

thank lot help!

edit: maybe looking for. thankful, if can comment on edit too.

4:    if (input.containskey(tclazz.getsimplename())) { 5:       jsonarray arr = input.getjsonarray(tclazz.getsimplename()); //valid??? 6:       (int = 0; < arr.size(); i++) { 7:          jsonobject obj = arr.getjsonobject(i); 8:          t myobj = myfactory.newobj(tclazz);             //now write fields using myobj.getallfields() or 9:       } 10:   }  11:   return result; 12:} 

use gson:

gson gson = new gson(); bufferedreader br = new bufferedreader(new filereader("c:\\file.json")); //convert json string object dataobject obj = gson.fromjson(br, dataobject.class); 

Comments