Say I have classes Foo
public class Foo {
private Bar bar;
}
and Bar
public class Bar {
private String fizz;
pr
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.