如何在使用gson解析json文件时重用代码?

时间:2016-09-07 02:14:21

标签: java json polymorphism gson

当我使用gson解析json文件时遇到了问题。我想反序列化一些类似的json文件 对我的对象。我键入了一个方法来完成这项工作,但我不知道如何将此方法应用于不同的json文件。这些json文件有一些类似的结构,所以我想将它们反序列化为相同超类型的子类型。

    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;
}

如上面的代码,我想通过将 PatternDetectionRequestBody 更改为某些兄弟类来使用此代码来解析不同的json文件。谁能告诉我怎么做?

1 个答案:

答案 0 :(得分:0)

难道你不能这样做吗? Class<? extends ParentOfYourObject>
编辑
做了这样的试验,并且它起作用了。

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());
        }
    }