I am understanding below JSON
{ "id": "1", "value": "some value" }
{ "id": "2", "value": null }
{ "id": "3" }
To hold the above JSON data I have java class :
class myClass
{
private String id;
private String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
In above example : id 2 and id 3 both have value as NULL
In java it is very difficult to identify the distinguish between passed null value in JSON and other field which are not passed hence java pojo has its default value as NULL.
For me value of id 2 & id 3 should not be same.
Is it possible to distinguish between provided JSON NULL & and default NULL in java?
keys(theObject) will contain the key if the value is set to null or undefined. Also theObject. hasOwnProperty(...) will let you know. So convert the JSON to an object and inspect the keys to see if the value was marshalled as undefined, null, or not present.
@arvin_codeHunk, null is an empty object, whereas "null" is an actual string containing the characters 'n', 'u', 'l', and 'l'. The String here is written as null telling you that you just took the String value of null which is equal to "null" . So a null will not be equal to "null" literal.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
It's better not to distinguish null
and missing values at all for the very reason you have to ask this question: This distinction is not easy and may not be possible with all JSON libraries, especially when automatically converting to POJO.
It depends on the JSON library if it works, but you can try to add an additional flag to your POJOs, that is set when the setter is called. For example like this:
class MyClass {
private String value;
private boolean isSetValue;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
isSetValue = true;
}
public boolean getIsSetValue() {
return isSetValue;
}
}
If you plan to serialize this POJO, you need to exclude getIsSetValue
from serialization and you likely need to modify the JSON serializer to use getIsSetValue
to decide whether to write a null
value or no value at all.
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