Java java.lang.UnsupportedOperationException: null问题解决

问题描述:

java.lang.UnsupportedOperationException: null

问题分析:

1、使用Gson进行序列化,但是使用fastjson进行反序列化,由于fastjson不支持Gson序列化LocalDate、LocalDateTime类型数据之后的json数据,导致报错。

        List 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}}}]

解决办法:

1、使用Gson进行反序列化。

        List 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>() {
        }.getType());

2、序列化和反序列化方式保持不变,LocalDate、LocalDateTime类型在序列化之前转换为String类型。

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

你可能感兴趣的:(序列化,java,json,开发语言)