Omer
Omer

Reputation: 544

JSON Element isJsonNull true on {} values

I have the following JSON response and I am using GSON google Java lib 2.3.1 for parsing JSON objects.

{
    "ClubName": "Test 3 Day",
    "Date": {},
    "CurrentSeqNo": {},
    "Logo": "/online/devadehil/club.png",
    "IsDateDisplayed": "false",
    "Secured": "false"    
}

I am using Java code as follows:

JsonElement elem = response.get("Date");
 if(!elem.isJsonNull()) //set to true
  elem.getAsString(); // throws exception here 

Exception:

java.lang.UnsupportedOperationException: JsonObject

Upvotes: 1

Views: 2726

Answers (1)

Konrad Krakowiak
Konrad Krakowiak

Reputation: 12365

You had exception because you call getAsString() method on JsonObject instance. Default implementation of this method is:

public String getAsString() {
   throw new UnsupportedOperationException(getClass().getSimpleName());
}

and it is override only on JsonArray and JsonPrimitive class.

You cannot use this method for JsonObject instance.

You can edit condition in your code like this : if(!elem.isJsonNull() && !elem.isJsonObject())

Upvotes: 4

Related Questions