RoeJi
RoeJi

Reputation: 31

Java Jackson | How to serialize object specifying concrete interface

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 {
}

And class implementing User interface:

public class UserImpl implements User {
    // implementation omitted
}

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

Exmaples:

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

Upvotes: 1

Views: 1933

Answers (1)

zappcity
zappcity

Reputation: 76

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\"}");
}

Upvotes: 4

Related Questions