Home > Mobile >  How to not proceed serialization of whole object if one or more required fields have null value?
How to not proceed serialization of whole object if one or more required fields have null value?

Time:10-30

I have next big JSON...

{
  "field1": "value1",
  "field2": "value2",
  ...
  "field100": "value100",
}

...and appropriate POJO

@Builder
@Data
public class BigJsonDto{
    private String field1;
    private String field2;

    private String field100;
}

Let's say all fields are required and nullable except field1 that can't have a null value. So I want to tell Jackson (or another way) stop serialization if one or more required fields have null value rather than just ignore it (with @JsonInclude). How can I reach it?

It would be nice if it's possible to use built-in ObjectMapper.

I tried to use @JsonProperty(required = true) annotation but as I can see this annotation is used in deserialization. So in this case I got required fields with null values.

CodePudding user response:

I think you can add the @NonNull annotation to the field you require to not be null. Then you can try to handle the exception whenever you build the BigJsonDto object. For example the code below will throw the following exception

Exception in thread "main" java.lang.NullPointerException: field1 is marked non-null but is null
    at BigJsonDto.<init>(StackOverflowQuestion.java:21)
    at BigJsonDto$BigJsonDtoBuilder.build(StackOverflowQuestion.java:21)
    at StackOverflowQuestion.main(StackOverflowQuestion.java:16)
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Data;
import lombok.NonNull;

public class StackOverflowQuestion {

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        var output = mapper.writeValueAsString(
                BigJsonDto.builder()
                        // uncomment this line to not throw exception
                        //.field1("a")
                        .field2("b")
                        .field100("c").build());
        System.out.println(output);
    }
}

@Builder
@Data
class BigJsonDto {
    @NonNull
    private String field1;
    private String field2;
    private String field100;

}
  • Related