1

I am using net.sf.json.JSONObject. It will remove key if my value is null while I am trying to put data in Json object using put method.

Is there any way to keep my key as it is in my object even my value is null?

for ex.

 JSONObject json = new JSONObject();
 json.put("myKey",null);

Then my output is : {}

But I want

output : {"myKey",""}

How can I do?

Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82

3 Answers3

7
json.put("myKeyu",JSONObject.NULL);

More details here.

Archer
  • 5,073
  • 8
  • 50
  • 96
  • Hi..it is n't possible in my case..my value is coming dynamically from database. So it may be null or not. – Vishal Zanzrukia Sep 21 '13 at 12:18
  • 2
    why not to do this: json.put("myKeyu",value == null?JSONObject.NULL:value); – Archer Sep 21 '13 at 12:36
  • yes you are right..we can do but I already developed my application and I want some global solution by which I have to change at only one place..in your case whenever I put value in json, I have to do change..can't it be possible by some JsonConfig? – Vishal Zanzrukia Sep 21 '13 at 12:51
  • No. I doubt it's possible to do through JsonConfig. I think you can try using AOP: http://stackoverflow.com/questions/4829088/java-aspect-oriented-programming-with-annotations and intercept all JSONObject.put methods and replace your null with JSONObject.NULL. – Archer Sep 21 '13 at 12:54
1

JSONObject.NULL is for Apache Commons JSONObject.

Try the following instead:

json.put("key", JSONNull.getInstance())

Here follows the documentation for net.sf.json.JSONObject:
http://json-lib.sourceforge.net/apidocs/index.html

Search for JSONNull to find out more.

Tim Visée
  • 2,988
  • 4
  • 45
  • 55
asayamakk
  • 143
  • 2
  • 9
-2
JSONObject backJsonObject = new JSONObject();
        backJsonObject.put("111", "NULL");
        backJsonObject.put("111", "null");  how to output {"111":"null"} instead of  {"111":null}  in net.sf.json
kirti
  • 4,499
  • 4
  • 31
  • 60
Wei Du
  • 1