将整数转换为布尔值

2022-09-01 16:58:10

有没有办法将整数/短整值转换为布尔值?我收到的 JSON 如下所示:

{ is_user: "0", is_guest: "0" }

我正在尝试将其序列化为如下所示的类型:

class UserInfo {

    @SerializedName("is_user")
    private boolean isUser;

    @SerializedName("is_guest")
    private boolean isGuest;

    /* ... */
}

如何使 Gson 将这些 int/short 字段转换为布尔值?


答案 1

从获取 Gson 2.2.2 或更高版本开始。早期版本(包括 2.2)不支持基元类型的类型适配器。接下来,编写一个将整数转换为布尔值的类型适配器:

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

...然后使用此代码创建 Gson 实例:

  Gson gson = new GsonBuilder()
      .registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
      .registerTypeAdapter(boolean.class, booleanAsIntAdapter)
      .create();

答案 2

如果你把它们作为int或短裤来读,那么你可以

boolean b = (i != 0)

其中 b 是您要获取的布尔值,i 是整数或短整型值。

如果你把它们读成字符串,那么你需要

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

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