自学内容网 自学内容网

自定义反序列化过程

需求:student对象中name属性,序列化时将该属性映射为stuname,反序列化时将 Json中的NAME键值对映射到name属性中

   @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    static class Student {

        @JsonProperty("stuname")
        private List<String> name;

        @JsonProperty("age")
        private String age;

        @Override
        public String toString() {
            return "Student{" +
                    "name=" + name +
                    ", age='" + age + '\'' +
                    '}';
        }
    }
public class StudentDeserializer extends JsonDeserializer<Student> {
        @Override
        public Student deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            // 自定义反序列化逻辑
            Student student = new Student();
            JsonNode node = p.getCodec().readTree(p);
            JsonNode namesNode = node.get("NAMES");
            ObjectMapper objectMapper = new ObjectMapper();
            List<String> names = objectMapper.convertValue(namesNode, objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
            JsonNode ageNode = node.get("age");
            String age = objectMapper.convertValue(ageNode, String.class);
            student.setName(names);
            student.setAge(age);
            return student;
        }
  @Test
    public void stuTest() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        // 创建一个Student对象并序列化为JSON
        Student student = new Student();
        student.setName(Arrays.asList("John Doe", "Jane Doe"));
        student.setAge("1");
        String jsonString = mapper.writeValueAsString(student);
        System.out.println("Serialized JSON: " + jsonString);

        // 反序列化JSON字符串为Student对象
        // 注意这里的JSON字符串中NAMES是一个数组
        String inputJson = "{\"NAMES\":[\"Alice\", \"Bob\"],\"age\":\"15\"}";
        // 在 ObjectMapper 上注册反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Student.class, new StudentDeserializer());
        mapper.registerModule(module);
        Student deserializedStudent = mapper.readValue(inputJson, Student.class);
        System.out.println("Deserialized Student: " + deserializedStudent);
    }


原文地址:https://blog.csdn.net/Dy_1748204009/article/details/143778031

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!