problem description
java.lang.UnsupportedOperationException: null
problem analysis
- 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
- 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());
- 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);