Search code examples
javajsonserializationdeserializationfasterxml

How to erase a type of instance when serializing/deserializing JSON?


I use fasterxml to serialize/deserialize JSON

public class A {
    String field;
    B b;
}

public class B {
    int n;
}

I want to get a JSON in format like this

{
  "field": "abc",
  "n": 123
}

Is it possible?


Solution

  • You can simply use @JsonUnwrapped. No custom serializers are needed:

    public class A {
        public String field;
        @JsonUnwrapped
        public B b;
    }
    
    public class B {
        public int n;
    }
    

    Pay attention to the fields accessibility or it will not work.