Search code examples
javajacksonfasterxml

How to customize serializing of java object


How to serialize that object. But only with fields of object anotherObject but without "anotherObject" key in json

class A{
   int some = 1;
   B anotherObject = new B();
}

class B{
    int someB = 2;
}

I need as serializing result next JSON

{
    "A":{
       some: 1,
       anotherSome: 2
    }
}

Solution

  • You can use @JsonUnwrapped annotation.

    class A {
        @JsonProperty
        int some = 1;
    
        @JsonUnwrapped
        B anotherObject = new B();
    }
    
    class B {
        @JsonProperty
        int someB = 2;
    }