Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.fasterxml.jackson.annotation.JsonSubTypes;
- import com.fasterxml.jackson.annotation.JsonTypeInfo;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.fasterxml.jackson.databind.SerializationFeature;
- import org.junit.Assert;
- public class TestSerialization {
- @JsonTypeInfo( use=JsonTypeInfo.Id.CLASS)
- @JsonSubTypes({ @JsonSubTypes.Type(value = AImpl1.class), @JsonSubTypes.Type(value = AImpl2.class)})
- public static interface A {
- public String foo();
- }
- public static class AImpl1 implements A {
- String s;
- public AImpl1(){};
- public AImpl1(String s){
- this.s = s;
- }
- public String getS() {
- return s;
- }
- public void setS(String s) {
- this.s = s;
- }
- public String foo() {
- return s;
- }
- @Override public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
- AImpl1 aImpl1 = (AImpl1) o;
- return !(s != null ? !s.equals(aImpl1.s) : aImpl1.s != null);
- }
- }
- public static class AImpl2 implements A {
- int i;
- public AImpl2(){};
- public AImpl2(int i) {
- this.i = i;
- }
- public int getI() {
- return i;
- }
- public void setI(int i) {
- this.i = i;
- }
- public String foo() {
- return Integer.toString(i);
- }
- @Override public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
- AImpl2 aImpl2 = (AImpl2) o;
- return i == aImpl2.i;
- }
- }
- @JsonTypeInfo( use=JsonTypeInfo.Id.CLASS)
- @JsonSubTypes({ @JsonSubTypes.Type(value = BImpl.class)})
- public static interface B {
- }
- public static class BImpl implements B {
- A a;
- public BImpl(){};
- public BImpl(A a) {
- this.a = a;
- }
- public A getA() {
- return a;
- }
- public void setA(A a) {
- this.a = a;
- }
- @Override public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
- BImpl b = (BImpl) o;
- return !(a != null ? !a.equals(b.a) : b.a != null);
- }
- }
- @org.junit.Test
- public void testSerialisation() throws Exception {
- ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
- A a1 = new AImpl1("ggfd");
- A a2 = new AImpl2(5);
- B b1 = new BImpl(a1);
- B b2 = new BImpl(a2);
- String s1 = objectMapper.writeValueAsString(b1);
- String s2 = objectMapper.writeValueAsString(b2);
- B serializedB1 = objectMapper.readValue(s1, B.class);
- B serializedB2 = objectMapper.readValue(s2, B.class);
- Assert.assertEquals(b1, serializedB1);
- Assert.assertEquals(b2, serializedB2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement