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

sudheer mishra :

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?

kapex :

It's better not to distinguish null and missing values at all for the very reason you have to ask this question: This distinction may not be possible with all JSON libraries, especially when automatically converting to POJO.

It depends on the JOSN 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71283&siteId=1