Jackson custom value for nested class’s field

Good day everyone, Im struggling with serializing object with nested object having custom name with @ JsonProperty. So, here it is:

public class Wrapper {

public final Payload payload;

public Wrapper(String name){
this.payload = new Payload(name);
}    

public static final class Payload{
@JsonProperty("customName")
public final String name;

@JsonCreator
public Payload(@JsonProperty ("customName") String name){

this.name = name;
}
}


}

So, in every test I see non-custom name – “name”. I added getter with @JsonProperty without any success.

My test class:

@JsonTest
public class SerializeWrapperTest {


    @Test
    void whenSerialiseThanCorrect() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Wrapper wrapper =
                new Wrapper("name");
        String json = objectMapper.writeValueAsString(wrapper);
        Assertions.assertEquals("{"payload":{"customName":"name"}}",json);
    }
}

Test results: Expected :{“payload”:{“customName”:”name”}} Actual :{“payload”:{“name”:”name”}}

org.opentest4j.AssertionFailedError.

Edited.

Answer

If I understood it correct , you need to have a custom property in json for the field , “name”. For that you need to do following –

     public class Wrapper {

    public final Payload payload;

    public Wrapper(String name){
        this.payload = new Payload(name);
    }

    public static final class Payload{
        @JsonProperty("customName")
        public final String name;

        public Payload(String name){

            this.name = name;
        }
    }

JUnit –

public class WrapperTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void whenSerialiseThanCorrect() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Wrapper wrapper =
                new Wrapper("Ajeet");
        String json = objectMapper.writeValueAsString(wrapper);
        System.out.println(json);
    }
}

enter image description here

}

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *