I have a simple case where I want to enforce null check on values found in JSON string when converting the JSON string to POJO using Jackson (2.8) and Lombok (latest version) in Java8. But it looks like @NonNull
doesn't throw exception when the pojo is created using ObjectMapper.convertValue
, but it works fine when pojo is created normally using builder pattern"?
here is my case:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Lombok;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class LearnJackson {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static void main(final String[] args) throws IOException {
learnToConvertJsonToSimplePojo();
}
public static void learnToConvertJsonToSimplePojo() throws IOException {
String jsonString = "{}";
JsonNode node = OBJECT_MAPPER.readValue(jsonString, JsonNode.class);
// this is supposed to throw NullPointerException
MySimplePojo o = OBJECT_MAPPER.convertValue(node, MySimplePojo.class);
log.info("o.getVar1: {}, o.getVar2: {}", o.getVar1(), o.getVar2()); // prints null
// MySimplePojo.builder().build(); // this throws NullPointerException correctly
}
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public static class MySimplePojo {
@NonNull
private String var1;
@NonNull
private List<String> var2;
}
}