Jackson Mapper serialize empty object instead of null

后端 未结 3 1096
梦毁少年i
梦毁少年i 2021-01-14 11:54

Say I have classes Foo

public class Foo {
    private Bar bar;
}

and Bar

public class Bar {
    private String fizz;
    pr         


        
3条回答
  •  太阳男子
    2021-01-14 12:13

    No. I don't see any way doing this. If you don't initialize your Bar, it'll be null inside the JSON.

    Since you can't alter these classes, you can just check if the Bar inside the Foo is null and if it is, just initialize it and you'll get what you want.

    Bar bar = foo.getBar();
    if (bar == null) {
        foo.setBar(new Bar());
    }
    String json = objectMapper.writeValueAsString(foo);
    

    The json will be the following:

    {
        "bar" : {
            "fizz" : null, 
            "bang" : null 
        } 
    }
    

    Hope this helps.

提交回复
热议问题