需求: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);
}