sudheer mishra
sudheer mishra

Reputation: 73

How to distinguish between JSON null value and default java null in java pojo

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?

Upvotes: 6

Views: 1581

Answers (3)

kapex
kapex

Reputation: 29999

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.

Upvotes: 3

Arnab Kundu
Arnab Kundu

Reputation: 1527

Use this code:

JSONObject jsonObject = new JSONObject(response);
Sting s =  jsonObject.optString("value");

for this { "id": "2", "value": null } it will return null as JAVA Sting

jsonObject.optString("value"); // s="null"

and for this { "id": "3" } it will return null value

jsonObject.optString("value"); // s==null

Upvotes: 0

jokster
jokster

Reputation: 577

The only possible solution I can imagine: Track calls to the setter and ensure that the jSON library you use sets explicit null values.

Would give the following results:

  • id 1: setter called with "some value"
  • id 2: setter called with null
  • id 3: setter NOT called

Alternative after Torbens comment: If the library doesn't use getters/setters, you might be able to use a special value for "unset" and mask that in the getter to return null instead.

Upvotes: 0

Related Questions