首页 > 解决方案 > 有什么办法可以减少代码量?

问题描述

我一直在做一个学习项目,看起来不错,但我想让它尽可能好。我有两个单独的 JSON 文件,包含用户和操作。我需要提取该数据并对其进行一些处理。但问题是关于获取这些数据。我有一个名为 DataReader 的类,它有两种方法——readUsers 和 readActions。

public class DataReader {
    Gson gson = new GsonBuilder().setDateFormat("MM.dd").create();

    public ArrayList<Action> readActions(String fileName)
            throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        Type actionsArrayList = new TypeToken<ArrayList<Action>>() {
        }.getType();
        return gson.fromJson(new FileReader(fileName), actionsArrayList);
    }

    public HashMap<Integer, User> readUsers(String fileName)
            throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        Type usersHashMap = new TypeToken<HashMap<Integer, User>>() {
        }.getType();
        return gson.fromJson(new FileReader(fileName), usersHashMap);
    }
}

如您所见,这两种方法做的事情几乎相同,不同之处仅在于它返回和从该 JSON 文件中获取的对象类型。

那么有没有可能制作一个这样的方法readData,只获取fileName参数并自行排序以减少代码量?

标签: javagson

解决方案


也许你可以试试这个。


public<T> T readData(String fileName,TypeToken<T> typeRef)
            throws JsonIOException, JsonSyntaxException, FileNotFoundException {

   return gson.fromJson(new FileReader(fileName), typeRef);
}


// make a type class , e.g: MyGsonTypes
public final class MyGsonTypes{

   public static final TypeToken<HashMap<Integer, User>> usersHashMapType = new TypeToken<HashMap<Integer, User>>(){}.getType();

}


// when you use it
var data = readData("1.json", MyGsonTypes.usersHashMapType);


推荐阅读