Java java.lang.UnsupportedOperationException: null

created at 05-18-2022 views: 22

problem description

java.lang.UnsupportedOperationException: null

problem analysis

  1. Use Gson for serialization, but use fastjson for deserialization, because fastjson does not support Gson to serialize json data after LocalDate, LocalDateTime type data, resulting in an error.
        List<TestModel> testModelList = new ArrayList<>();
        TestModel testModel = new TestModel();
        testModel.setLocalDate(LocalDate.now());
        testModel.setLocalDateTime(LocalDateTime.now());
        testModelList.add(testModel);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(testModelList);
        testModelList = JSONObject.parseArray(jsonStr, TestModel.class);
[{"localDate":{"year":2022,"month":5,"day":18},"localDateTime":{"date":{"year":2022,"month":5,"day":18},"time":{"hour":10,"minute":27,"second":34,"nano":979527900}}}]

solution

  1. Use Gson for deserialization.
        List<TestModel> testModelList = new ArrayList<>();
        TestModel testModel = new TestModel();
        testModel.setLocalDate(LocalDate.now());
        testModel.setLocalDateTime(LocalDateTime.now());
        testModelList.add(testModel);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(testModelList);
        testModelList = gson.fromJson(jsonStr, new TypeToken<List<TestModel>>() {
        }.getType());
  1. The serialization and deserialization methods remain unchanged. The LocalDate and LocalDateTime types are converted to String types before serialization.
        List<TestModel> testModelList = new ArrayList<>();
        TestModel testModel = new TestModel();
        testModel.setLocalDateStr(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        testModel.setLocalDateTimeStr(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        testModelList.add(testModel);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(testModelList);
        testModelList = JSONObject.parseArray(jsonStr, TestModel.class);
created at:05-18-2022
edited at: 05-30-2022: