爪哇杰克逊|如何序列化指定具体接口的对象 [英] Java Jackson | How to serialize object specifying concrete interface

查看:57
本文介绍了爪哇杰克逊|如何序列化指定具体接口的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们已经给出了 Java 接口:

Let's assume we have given Java interfaces:

public interface UserA {
    String getLogin();
    void setLogin(final String login);
}

public interface UserB {
    String getPassword();
    void setPassword(final String password);
}

public interface UserC {
    String getEmail();
    void setEmail(final String email);
}

以及扩展上述所有内容的接口:

And interface extending all of above:

public interface User extends UserA, UserB, UserC {
}

和实现用户界面的类:

public class UserImpl implements User {
    // implementation omitted
}

现在,我想序列化 UserImpl 对象,选择小"接口(UserA、UserB、UserC)或大"接口(User)之一.

Now, I'd like to serialize UserImpl object choosing one of 'small' interfaces (UserA, UserB, UserC) or the 'big' one (User).

示例:

  • UserA 界面的预期结果

  • expected result for UserA interface

{登录":约翰"}

UserB 界面的预期结果

expected result for UserB interface

{ 密码:JohnSnow"}

{ password : "JohnSnow" }

用户界面的预期结果

{ "login" : "John", 密码: "JohnSnow", "email": "john@snow.com" }

{ "login" : "John", password : "JohnSnow", "email" : "john@snow.com" }

是否有任何方法可以通过将对象的接口之一传递给 Jackson 映射器来获得上述结果(通过切换接口更改 JSON)?

Is there any method to get above result (changing JSON by switching interface) by passing one of object's interfaces to the Jackson mapper?

推荐答案

使用 ObjectMapper#writerFor 来选择序列化时应该使用哪个接口.这是显示此功能的通过测试.如果您使用的是没有 writerFor 的旧版本 Jackson,那么您可以使用 writerWithType.

Use ObjectMapper#writerFor to choose which interface should be used when serializing. Here is a passing test that shows this functionality. If you are using an old version of Jackson that doesn't have writerFor then you can use writerWithType.

public interface A {
    String getStringA();
}

public interface B {
    String getStringB();
}

public class AB implements A, B {

    @Override
    public String getStringA() {
        return "value a";
    }

    @Override
    public String getStringB() {
        return "value b";
    }
}

@Test
public void t() throws JsonProcessingException {
    final ObjectMapper mapper = new ObjectMapper();

    final String a = mapper.writerFor(A.class).writeValueAsString(new AB());
    assertThat(a).isEqualTo("{\"stringA\":\"value a\"}");

    final String b = mapper.writerFor(B.class).writeValueAsString(new AB());
    assertThat(b).isEqualTo("{\"stringB\":\"value b\"}");
}

这篇关于爪哇杰克逊|如何序列化指定具体接口的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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