3

I'm trying to make an API backward-compatible by checking a value.

I have to determine if one of the parameters is a string or a JsonObject.

This is what I tried:

if (oDevices.get(i).getAsJsonPrimitive().isJsonObject()) {
                  deviceToClean.addProperty("deviceId", oDevices.get(i).getAsJsonObject().get("name").getAsString());
              } else if(oDevices.get(i).getAsJsonPrimitive().isString()) {
                  deviceToClean.addProperty("deviceId", oDevices.get(i).getAsString());
              }

When I send a JsonObject to the API, I get the following error:

This is not a JSON Primitive.

How I can check whether oDevices.get(i) is a json object or a string?

1 Answer 1

12

You are always getting the value as primitive.

Change this:

if (oDevices.get(i).getAsJsonPrimitive().isJsonObject()) {

to

if (oDevices.get(i).isJsonObject()) {

I would also change this:

if(oDevices.get(i).getAsJsonPrimitive().isString()) {

To this:

if(oDevices.get(i).isJsonPrimitive() && oDevices.get(i).getAsJsonPrimitive().isString()) {

// ----------------^ check if it's a json primitive before getting its value
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @BackSlash. I thought the isJsonObject() method does not exists on a simple JsonElement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.