如何使用jackson mixins将json映射到具有不同结构的java对象 [英] how to map json to java object having a different structure using jackson mixins

查看:575
本文介绍了如何使用jackson mixins将json映射到具有不同结构的java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换此json

{
    "name": "abc",
    "city": "xyz"
}

使用Jackson mixin的员工对象

to employee object using Jackson mixin

//3rd party class//
public class Employee {
    public String name;
    public Address address;
}

//3rd party class//
public class Address {
    public String city;
}


推荐答案

通常,你会注释地址字段,其中 @JsonUnwrapped 在序列化时被解包(并在反序列化时被包装)。但是因为你不能改变你的第三方课程,你必须在mixin上这样做:

Usually, you would annotate the address field with @JsonUnwrapped to be unwrapped when serialized (and wrapped when deserialized). But as you cannot change your 3rd party classes, you have to do this on a mixin instead:

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

然后,创建一个包含所有特定扩展名的模块。这可以通过继承模块 SimpleModule ,或者通过编写 SimpleModule 如下:

Then, create a module that holds all your specific "extensions". This can be done by subclassing Module or SimpleModule, or by composing a SimpleModule as here:

SimpleModule module = new SimpleModule("Employee");
module.setMixInAnnotation(Employee.class, EmployeeMixin.class);

第三,用 ObjectMapper 注册模块:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

最后,有趣的序列化/反序列化!

Last, have fun serializing/deserializing!

自包含的完整示例,即子类 SimpleModule

Self contained, complete example that subclasses 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

这篇关于如何使用jackson mixins将json映射到具有不同结构的java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆