Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to put null values in JSON object

Tags:

java

json

android

I am trying to pass parameter to api using JSON.

class Sample { ...    String token; ...  void method() { ...     JSONObject params = new JSONObject();     params.put(KEY_TOKEN,token);     params.put(KEY_DATE,date);      Log.e("params ",params+"");         ...  }     

I get the value of params as {"date":"2017-06-19"} but token is seen nowhere. I have not initialized token and its value is null as its an instance variable. So is it something that uninitialized value are not included?

like image 792
Aishwarya Avatar asked Jun 19 '17 13:06

Aishwarya


People also ask

Can a JSON object have null values?

Null values JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How do I allow null values in JSON?

To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option. If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.

Can you send null in JSON?

If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.

Can a JSON object have a null key?

JSON has two types of null value When the key is provided, and the value is explicitly stated as null . When the key is not provided, and the value is implicitly null .


1 Answers

Right there in the documentation, in the first paragraph:

Values may not be null, NaNs, infinities, or of any type not listed here.

So yes, it is "...something that null values are not included..." (edit: that was a quote from your original question; your updated question changes it to "uninitialized values" but the default value of an object reference is null, so...)

It's a "feature" of that class, though; JSON itself understands null just fine. Further down in the documentation it says you use a "sentinal value," NULL, to represent null. Which seems...odd. There's a note about it:

Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value NULL. In particular, calling put(name, null) removes the named entry from the object but put(name, JSONObject.NULL) stores an entry whose value is JSONObject.NULL.

So:

params.put(KEY_TOKEN, token == null ? JSONObject.NULL : token); 
like image 143
T.J. Crowder Avatar answered Oct 03 '22 21:10

T.J. Crowder