java - 将 int 转换为 boolean 值

标签 java json gson

有没有办法可以将 int/short 值转换为 boolean 值?我收到的 JSON 格式如下:

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

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

class UserInfo {

    @SerializedName("is_user")
    private boolean isUser;

    @SerializedName("is_guest")
    private boolean isGuest;

    /* ... */
}

如何让 Gson 将这些 int/short 字段转换为 boolean 值?

最佳答案

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

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

关于java - 将 int 转换为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11399079/

相关文章:

Java 整数/ double 到无符号字节

java - 使用 ImageIO.write jpg 文件 : pink background 的问题

java - 动态窗口大小和按钮

javascript - JavaScript 中的数组 JSON

java - 具有多个依赖项的 Dagger2 组件

json - 使用 Jackson 在 Scala 中将 List[Any] 序列化到/从 Json

sql-server - 使用 Entity Framework 发布 Web API 时出错

java - 解析包含多个嵌套对象的 JSON 对象而不为每个嵌套对象创建类

java - 为什么Gson fromJson会抛出JsonSyntaxException : Expected BEGIN_OBJECT but was BEGIN_ARRAY?

android - 使用 GSON 从 Web 服务检索数据时遇到问题