JsonNullable is a commonly used object in PHP. It always has the characteristic that the isPresent value is true. This means that a JsonNullable object is considered present regardless of whether it is null or not. PHP editor Xinyi will explore the uses and characteristics of the JsonNullable object in the following article, and explain why its isPresent value is always true. By in-depth understanding of the JsonNullable object, we can better understand its application and advantages in PHP development.
I have a file in json format. It stores json objects that I use in my tests. I used objectmapper to convert this file to objects and it converted fine, but there is a problem. All fields in the object have a wrapper type of jsonnullabel. The problem is as follows - all jsonnullabel objects, even if they contain null attribute value ispresent = true. Therefore, the "orelse" and "ispresent" methods do not work properly. I got npe. How can I ensure that when converting from a string or json file, these fields equal "false" if there are null values inside?
json example:
65bee5661098cI have tried this configuration for objectmapper: Object mapper configuration:
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(new Jdk8Module()); objectMapper.registerModule(new JsonNullableModule()); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
Try using @jsondeserialize jackson annotation on the class member, the annotation can be null in json, and you want the value to be "false" instead of null, like this:
public class MyJsonClass { @JsonDeserialize(using = CustomDeserializer.class) public String nullableMember; } public class CustomDeserializer extends StdDeserializer<String> { public CustomDeserializer() { this(null); } public CustomDeserializer(Class<?> vc) { super(vc); } @Override public String deserialize(JsonParser jsonparser, DeserializationContext context) { String text = jsonparser.getText(); if (null == text) { text = "false"; } return text; } }
The above is the detailed content of JsonNullable objects always have isPresent value = true. For more information, please follow other related articles on the PHP Chinese website!