如何转换此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;
}
答案 0 :(得分:2)
通常,您会在序列化时将address
字段注释为@JsonUnwrapped
并将其解包(并在反序列化时包装)。但是,由于您无法更改第三方课程,因此您必须在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));
}
}