需求:student对象中name属性,序列化时将该属性映射为stuname,反序列化时将 Json中的NAME键值对映射到name属性中
java"> @AllArgsConstructor@NoArgsConstructor@Getter@Setterstatic class Student {@JsonProperty("stuname")private List<String> name;@JsonProperty("age")private String age;@Overridepublic String toString() {return "Student{" +"name=" + name +", age='" + age + '\'' +'}';}}
java">public class StudentDeserializer extends JsonDeserializer<Student> {@Overridepublic 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;}
java"> @Testpublic void stuTest() throws IOException {ObjectMapper mapper = new ObjectMapper();// 创建一个Student对象并序列化为JSONStudent 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);}