如何转换这个json
{
"name": "abc",
"city": "xyz"
}
使用 Jackson mixin 到员工对象
//3rd party class//
public class Employee {
public String name;
public Address address;
}
//3rd party class//
public class Address {
public String city;
}
最佳答案
通常,您可以使用 @JsonUnwrapped
注释 address
字段,以便在序列化时解开包装(并在反序列化时包装)。但由于您无法更改第 3 方类,因此您必须在 mixin 上执行此操作:
// Mixin for class Employee
abstract class EmployeeMixin {
@JsonUnwrapped public Address address;
}
然后,创建一个包含所有特定“扩展”的模块。这可以通过子类化 Module
或 SimpleModule
来完成,或者通过如下组合 SimpleModule
来完成:
SimpleModule module = new SimpleModule("Employee");
module.setMixInAnnotation(Employee.class, EmployeeMixin.class);
第三,使用您的ObjectMapper
注册模块:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
最后,享受序列化/反序列化的乐趣!
自包含的完整示例,子类 SimpleModule
:
public class TestJacksonMixin {
/* 3rd party */
public static class Employee {
public String name;
public Address address;
}
/* 3rd party */
public static class Address {
public String city;
}
/* Jackon Module for Employee */
public static class EmployeeModule extends SimpleModule {
abstract class EmployeeMixin {
@JsonUnwrapped
public Address address;
}
public EmployeeModule() {
super("Employee");
}
@Override
public void setupModule(SetupContext context) {
setMixInAnnotation(Employee.class, EmployeeMixin.class);
}
}
public static void main(String[] args) throws JsonProcessingException {
Employee emp = new Employee();
emp.name = "Bob";
emp.address = new Address();
emp.address.city = "New York";
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new EmployeeModule());
System.out.println(mapper.writeValueAsString(emp));
}
}
关于java - 如何使用 Jackson Mixins 将 json 映射到具有不同结构的 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291640/