Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set a value to null with com.google.gson.JsonObject in java?

How do you set a value to null with com.google.gson.JsonObject in java? I can certainly read if a value is null by using isNull - but it seems like when I put null, it just ignores it:

JSONObject jsonObj = new JSONObject();
jsonobjToEra.addProperty("sun", Double.parseDouble(val));
jsonobjToEra.addProperty("mon", 22.333);
jsonobjToEra.addProperty("val", null); //ignoring it

Please note that I am using com.google.gson.JsonObject which is different from similar questions like How do you set a value to null with org.json.JSONObject in java? in other posts in this SO.

The JSON:

[
  {
    "sun": 1122435343453,
    "mon": 1460538600000,
    "val": 45.900001525878906
  },
  {
    "sun": 1460538600000,
    "mon": 1460538660000,
    "val": 45.900001525878906
  }
  ]
like image 732
My God Avatar asked Apr 14 '16 11:04

My God


People also ask

How do I put null values in Gson?

We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON.

How do you set a JSON object to null?

Null values Considering the previous example where JSON data with a null value is parsed into a data object, the following is true: id - If the property is defined as nillable in the schema, then it will be set to null. If the property is not defined as nillable, it will throw an exception.

Can a JSONObject be null?

JSONObject. NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined.

How do you initialize Gson?

You just have to call getInstance() function to get initialized gson object for ready to use. Every time it will not initialize new Gson object and reused old initialized object. This gson will be used as single Instance.


2 Answers

You can use com.google.gson.JsonNull.INSTANCE like this:

JsonObject jsonObj = ...
jsonObj.add("val", JsonNull.INSTANCE); 

Or if you want to complety remove value from serialization

jsonObj.remove("val");

Demo:

String json = "{\"a\": 1, \"b\": 1}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);

System.out.println(jsonObject); // {"a":1,"b":1}

jsonObject.addProperty("a", 2);
jsonObject.add("b", JsonNull.INSTANCE);
System.out.println(jsonObject); // {"a":2,"b":null}

jsonObject.remove("a");
System.out.println(jsonObject); // {"b":null}
like image 116
varren Avatar answered Oct 25 '22 07:10

varren


You need to use serializeNulls() of GsonBuilder. It enables Gson to serialize null fields.

EDIT

Usage of GsonBuilder

Gson gson = new GsonBuilder()
     .serializeNulls()
     .create();

Gson is made for converting Java objects to/from JSON. So you need to make a Data Structure or a class so that you can make an object of that and convert the whole object to json with null.

See this example

public class Country {

    String name;
    int population;
    private List<String> listOfStates;

    //getter and setter methods

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public List<String> getListOfStates() {
        return listOfStates;
    }

    public void setListOfStates(List<String> listOfStates) {
        this.listOfStates = listOfStates;
    }

}

And when you use it:

Country countryObj=new Country();
  countryObj.setName("India");
  countryObj.setPopulation(1000000);
  List<String> listOfStates=new ArrayList<String>();
  listOfStates.add("Madhya Pradesh");
  listOfStates.add("Maharastra");
  listOfStates.add("Rajasthan");
  
  countryObj.setListOfStates(listOfStates);
  Gson gson = new GsonBuilder()
     .serializeNulls()
     .create();
  
  // convert java object to JSON format,
  // and returned as JSON formatted string
  String json = gson.toJson(countryObj);
like image 44
rusted brain Avatar answered Oct 25 '22 07:10

rusted brain