Naftuli Tzvi Kay Naftuli Tzvi Kay - 1 year ago 34
Java Question

Convert ints to booleans

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 {

private boolean isUser;

private boolean isGuest;

/* ... */

How can I make Gson translate these int/short fields into booleans?

Answer Source

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) {
    } else {
  @Override public Boolean read(JsonReader in) throws IOException {
    JsonToken peek = in.peek();
    switch (peek) {
    case BOOLEAN:
      return in.nextBoolean();
    case NULL:
      return null;
    case NUMBER:
      return in.nextInt() != 0;
    case STRING:
      return Boolean.parseBoolean(in.nextString());
      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)