如何转换这个json
{
"name": "abc",
"city": "xyz"
}
使用杰克逊混入员工对象
//3rd party class//
public class Employee {
public String name;
public Address address;
}
//3rd party class//
public class Address {
public String city;
}
最佳答案
通常,您要在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));
}
}
见Jackson Annotations