有什么办法可以减少代码量?

时间:2020-03-06 01:48:47

标签: java gson

我一直在做一个研究项目,看起来不错,但我想使其尽可能好。我有两个单独的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文件返回并从该JSON文件获取的对象类型。

那么,是否有可能制作类似readData的方法,该方法仅获取fileName参数并自行处理,以减少代码量?

2 个答案:

答案 0 :(得分:1)

您需要关闭该Reader,特别是要创建的FileReader对象。您也不需要将Type定义为局部变量,因为这是不必要的。只是内联它。 您可以对其他方法执行相同的操作。

        public List<Action> readActionsSimplified(String fileName) throws IOException {
            try (Reader reader = new FileReader(fileName)) {
                return gson.fromJson(reader, new TypeToken<List<Action>>() {}.getType());
            }
        }

答案 1 :(得分:1)

也许您可以尝试一下。


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