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…):

JavaScript

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

JavaScript

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.

JavaScript

For primitive Type use below one

JavaScript

Enjoy the JSON parsing!

Advertisement