Skip to content
Advertisement

GSON Integer to Boolean for Specific Fields

I’m dealing with an API that sends back integers (1=true, other=false) to represent booleans.

I’ve seen this question and answer, but I need to be able to specify which field this should apply to, since some times an integer is actually an integer.

EDIT: The incoming JSON could possibly look like this (could also be String instead of int, etc…):

{ 
    "regular_int": 1234, 
    "int_that_should_be_a_boolean": 1
}

I need a way to specify that int_that_should_be_a_boolean should be parsed as a boolean and regular_int should be parsed as an integer.

Advertisement

Answer

We will provide Gson with a little hook, a custom deserializer for booleans, i.e. a class that implements the JsonDeserializer<Boolean> interface:

CustomBooleanTypeAdapter

import java.lang.reflect.Type;
import com.google.gson.*;
class BooleanTypeAdapter implements JsonDeserializer<Boolean> {
public Boolean deserialize(JsonElement json, Type typeOfT,
                           JsonDeserializationContext context) throws JsonParseException {
    if (((JsonPrimitive) json).isBoolean()) {
        return json.getAsBoolean();
    }
    if (((JsonPrimitive) json).isString()) {
        String jsonValue = json.getAsString();
        if (jsonValue.equalsIgnoreCase("true")) {
            return true;
        } else if (jsonValue.equalsIgnoreCase("false")) {
            return false;
        } else {
            return null;
        }
    }

    int code = json.getAsInt();
    return code == 0 ? false :
            code == 1 ? true : null;
  }
}

To use it we’ll need to change a little the way we get the Gson mapper instance, using a factory object, the GsonBuilder, a common pattern way to use GSON is here.

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();

For primitive Type use below one

 GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
    Gson gson = builder.create();

Enjoy the JSON parsing!

Advertisement