Naftuli Kay
Naftuli Kay

Reputation: 91740

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 {

    @SerializedName("is_user")
    private boolean isUser;

    @SerializedName("is_guest")
    private boolean isGuest;

    /* ... */
}

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

Upvotes: 26

Views: 11551

Answers (2)

Jesse Wilson
Jesse Wilson

Reputation: 40613

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();

Upvotes: 51

corsiKa
corsiKa

Reputation: 82589

If you're reading them in as ints or shorts, then you can just

boolean b = (i != 0)

Where b is the boolean you want to get and i is the int or short value.

If you're reading them in as Strings then you want

boolean b = !s.equals("0"); // use this if you WANT null pointer exception
                            // if the string is null, useful for catching
                            // bugs

or

boolean b = !"0".equals(s); // avoids null pointer exception, but may silently
                            // let a bug through

Upvotes: 0

Related Questions