0

I'm reading the JSONObject as input and i am retrieving the value of key "id" using getString() method of net.sf.json API but i'm curious to know why it is not going in the if block..

INPUT:
    {
    "id" : null
    }

code:

//reading the jsonObject from String
JSONObject jsonObject.fromObject(someString);
String id = jsonObject.getString("id");
if( id == null)
{
        //the control is not going in this if condition
}
Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
Rekha
  • 1
  • 3

1 Answers1

0

use optString("id",null) after isNull() check when you not sure about JSON format will be same and to handle NPE.

JSONObject jO=jsonObject.fromObject(someString);
String id = jO.optString("id",null);
if(jO.isNull("id"))
{
    //the control is not going in this if condition
}
else{

}

or

jsonObject.optJSONObjet(String arg1)

read this

Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
  • can you tell me what this optString() will do and if i print the id value in this if block it prints "null" – Rekha Aug 22 '16 at 12:37