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



当我使用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文件。有人能告诉我怎么做吗?

你就不能这样做吗?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());
        }
    }  

最新更新