我正在处理一个发送回整数(1=true,其他=false)以表示 boolean 值的 API。
我看过 this question and answer , 但我需要能够指定这应该应用于哪个字段,因为有时一个整数实际上是一个整数。
编辑:传入的 JSON 可能看起来像这样(也可以是 String 而不是 int,等等...):
{
"regular_int": 1234,
"int_that_should_be_a_boolean": 1
}
我需要一种方法来指定 int_that_should_be_a_boolean
应该被解析为 boolean 值,regular_int
应该被解析为整数。
最佳答案
我们将为 Gson 提供一个小钩子(Hook),一个用于 boolean 值的自定义反序列化器,即一个实现 JsonDeserializer<Boolean>
的类。接口(interface):
自定义 boolean 类型适配器
import java.lang.reflect.Type;
import com.google.gson.*;
class BooleanTypeAdapter implements JsonDeserializer<Boolean> {
public Boolean deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (((JsonPrimitive) json).isBoolean()) {
return json.getAsBoolean();
}
if (((JsonPrimitive) json).isString()) {
String jsonValue = json.getAsString();
if (jsonValue.equalsIgnoreCase("true")) {
return true;
} else if (jsonValue.equalsIgnoreCase("false")) {
return false;
} else {
return null;
}
}
int code = json.getAsInt();
return code == 0 ? false :
code == 1 ? true : null;
}
}
要使用它,我们需要稍微改变我们获取 Gson
的方式映射器实例,使用工厂对象 GsonBuilder,一种常见的模式使用方式 GSON
在这里。
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();
对于下面的原始类型使用
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();
享受JSON
解析!
关于java - GSON 整数到特定字段的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27176134/