I use Jackson Json Mapper to parse queries on my server.
For example, I'm waiting for query which fits class My_class
:
class My_class {
String a;
String b;
}
I deserialize queries this way:
public <T> T Deserialize(String json, Class<T> type) throws DeserializationException {
if (json == null || type == null) {
throw new IllegalArgumentException();
}
try {
return objectMapper.readValue(json, type);
} catch (JsonParseException e) {
throw new DeserializationException(e);
} catch (org.codehaus.jackson.map.JsonMappingException e) {
throw new DeserializationException(e);
} catch (IOException e) {
throw new DeserializationException(e);
}
}
Here are two example queries:
{"a":"test"}
{"a":"test", "b":null}
The problem is I want to know when a user sent me a query with only the field a
and when he sent a query with field b
set to null
. The mapper marks field b
as null
in both situations.
What is the better way to do this (and to avoid writing my own deserializer)?
You can use the method isNull()
to check if the JsonNode
is a null
literal.
boolean isNull()
Method that can be used to check if this node was created from JSON literal null value.
There is also isMissingNode()
, which seems to have a similar purpose. It should return true if the node isn't actually present in the JSON document. This method is useful e.g. if you want to use default values for properties that aren't set explicitly.
boolean isMissingNode()
Method that returns true for "virtual" nodes which represent missing entries constructed by path accessor methods when there is no actual node matching given criteria.
In my opinion you should avoid building something that depends on the difference between null
and missing nodes though. You are essentially adding some kind of additional data type to the deserialized JSON: instead of just null
most JSON APIs return in both cases, you now have null literal and missing node which is not a common practice. It is confusing and it may cause issues with your API because the client needs to do extra work to configure its serializer to distinguish those two states too. It's possible that not all JSON libraries support that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With