I ran into this problem in the context of SpringBoot, but it seems to be just a Jackson issue.
I have a DataObject which has several fields. The DataObject is contained within a Model. All the fields of DataObject are optional. But if all the fields are null, then I want the dataoObject itself to be null, but that doesn't seem to be the way it works.
Here my sample code
@Getter
@ToString
@NoArgsConstructor
public class TestContract {
private String field1;
@JsonUnwrapped
@Valid
private DataObject dataObject;
public static void main(String[] args) throws JsonProcessingException {
//language=JSON
String json = "{ \"field1\" : \"value1\"}";
ObjectMapper mapper = new ObjectMapper();
TestContract contract = mapper.readValue(json, TestContract.class);
System.out.println("contract: " + contract);
}
}
@Getter
@NoArgsConstructor
@ToString
public class DataObject {
private String nested1;
private String nested2;
}
The output I end up with is
contract: TestContract(field1=value1, dataObject=DataObject(nested1=null, nested2=null))
Is there any way to have the object end up as null?