Is there a way that I can convert int/short values to booleans? I'm receiving JSON that looks like this:
{ is_user: "0", is_guest: "0" }
I'm trying to serialize it into a type that looks like this:
class UserInfo { @SerializedName("is_user") private boolean isUser; @SerializedName("is_guest") private boolean isGuest; /* ... */ }
How can I make Gson translate these int/short fields into booleans?
You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.
Java For Testers To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .
Start by getting Gson 2.2.2 or later. Earlier versions (including 2.2) don't support type adapters for primitive types. Next, write a type adapter that converts integers to booleans:
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() { @Override public void write(JsonWriter out, Boolean value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(value); } } @Override public Boolean read(JsonReader in) throws IOException { JsonToken peek = in.peek(); switch (peek) { case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; case NUMBER: return in.nextInt() != 0; case STRING: return Boolean.parseBoolean(in.nextString()); default: throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek); } } };
... and then use this code to create the Gson instance:
Gson gson = new GsonBuilder() .registerTypeAdapter(Boolean.class, booleanAsIntAdapter) .registerTypeAdapter(boolean.class, booleanAsIntAdapter) .create();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With