如何使用jackson mixins将json映射到具有不同结构的java对象

时间:2016-10-27 18:20:55

标签: java json jackson

如何转换此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;
}

1 个答案:

答案 0 :(得分:2)

通常,您会在序列化时将address字段注释为@JsonUnwrapped并将其解包(并在反序列化时包装)。但是,由于您无法更改第三方课程,因此您必须在mixin上执行此操作:

// Mixin for class Employee
abstract class EmployeeMixin {
    @JsonUnwrapped public Address address;
}

然后,创建一个包含所有特定"扩展名"的模块。这可以通过继承ModuleSimpleModule或通过撰写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