Question

i have some java classes like MyClass1 and MyClass2 whose state is saved in json objects:

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

Now I want to write a generic method to parse the Json objects into Java objects using net.sf.json for help.

Let's start with MyClass1 - i want to create a List<MyClass1> containing the 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:       for (int i = 0; i < arr.size(); i++) {
7:          JSONObject obj = arr.getJSONObject(i);
8:          //now, how do I create an Object of type T?
9:       }
10:   }

11:   return result;
12:}

My first question is - is line 5 valid? My second question is in line 8: at some point I want to create an object of type T, is that possible?

Thank a lot for any help!

EDIT: maybe this is what I am looking for. I would be thankful, if you can comment on the edit too.

4:    if (input.containsKey(tClazz.getSimpleName())) {
5:       JSONArray arr = input.getJSONArray(tClazz.getSimpleName()); //VALID???
6:       for (int i = 0; i < arr.size(); i++) {
7:          JSONObject obj = arr.getJSONObject(i);
8:          T myObj = MyFactory.newObj(tClazz);
            //now write all fields using myObj.getAllFields() or something
9:       }
10:   }

11:   return result;
12:}
Was it helpful?

Solution

Use gson:

Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader("c:\\file.json"));
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top