Feng Weidong Feng Weidong - 3 months ago 21
JSON Question

How to re-use code when use gson to parse json file?

I got a problem when I use gson to parse json file. I want to deserialize some similar json files
to my objects. I typed a method to do this job, but I don't know how to apply this method to different json files. These json files have some similar structures, so I want to deserialize them into subtypes of the same supertypes.

private Map<String, PatternDetectionRequestBody> readRequestFromJson(File jsonFile) {
Map<String, PatternDetectionRequestBody> requestBodyMap = null;
try {
FileReader fileReader = new FileReader(jsonFile);
JsonReader jsonReader = new JsonReader(fileReader);
Gson gson = new Gson();
Type type = new TypeToken<Map<String, PatternDetectionRequestBody>>(){}.getType();
requestBodyMap = gson.fromJson(jsonReader, type);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return requestBodyMap;
}


As code above, I want to use this code to parse different json files by changing PatternDetectionRequestBody to some sibling classes. Could anyone tell me how to do this?

Answer

Can't you just do something like this? Class<? extends ParentOfYourObject>
EDIT
Did something like this for a trial, and it worked.

private static <T> Map<String, T> readRequestFromJson(File jsonFile, TypeToken<Map<String, T>> typeToken) {
        Map<String, T> requestBodyMap = null;
        try {

            FileReader fileReader = new FileReader(jsonFile);
            JsonReader jsonReader = new JsonReader(fileReader);
            Gson gson = new Gson();

            requestBodyMap = gson.fromJson(jsonReader,  typeToken.getType());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return requestBodyMap;
}  
public static void main(String[] args) throws Exception {

        Map<String, Person> myMap = (Map<String, Person>) readRequestFromJson(new File("C:/Users/User.Admin/Desktop/jsonFile"),
                new TypeToken<Map<String, Person>>() {
                });   

        for (Map.Entry<String, Person> entry : myMap.entrySet()) {
            System.out.println(entry.getValue().getFirstName());
        }
    }