一个API我的应用程序与通信发送看起来像这样的回应:Gson:处理可以返回不同基元类型的json对象字段?
{
id:12345,
active:1
}
的问题是,旧版本的API将响应字段作为一个布尔值,而不是像这样
{
id:12345,
active:false,
}
一个int
有了Gson,我怎么能在不知道哪个版本将被返回的情况下处理这两个问题?
一个API我的应用程序与通信发送看起来像这样的回应:Gson:处理可以返回不同基元类型的json对象字段?
{
id:12345,
active:1
}
的问题是,旧版本的API将响应字段作为一个布尔值,而不是像这样
{
id:12345,
active:false,
}
一个int
有了Gson,我怎么能在不知道哪个版本将被返回的情况下处理这两个问题?
注册一个CustomDeserializer布尔和当过任何物体内部遇到一个布尔值,GSON会尝试与你定义的规则来反序列化。
@Data
class JsonTestClass {
Boolean active = new Boolean(true);
Integer id;
}
class BooleanJsonDeserializer implements JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
if (jsonPrimitive.isBoolean()) {
return jsonPrimitive.getAsBoolean();
} else {
return jsonPrimitive.getAsInt() == 0 ? false : true;
}
}
}
// TempJson
public static void main(String[] args) throws Exception {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, new BooleanJsonDeserializer()).create();
System.out.println(gson.fromJson("{id:12345,active:1}", JsonTestClass.class).getActive());
System.out.println(gson.fromJson("{id:12345,active:0}", JsonTestClass.class).getActive());
System.out.println(gson.fromJson("{id:12345,active:false}", JsonTestClass.class).getActive());
System.out.println(gson.fromJson("{id:12345,active:true}", JsonTestClass.class).getActive());
}
输出:
true
false
false
true
我将标志着这个答案的最好的。只是一点点注意。由于Gson中的TypeAdapter是面向流的,而JsonDeserializer是面向树的,所以'BooleanJsonDeserializer'的名称比'BooleanTypeAdapter'更接近该类所做的描述。 –
@LyubomyrShaydariv更改了名称:)在向GSON注册TypeAdapter时使用了TypeAdapter –
PFB处理此问题的方式。
public static void main(String[] args) {
Gson gson = new Gson();
JsonObject obj = gson.fromJson("{ id:12345, active:1}", JsonObject.class);
JsonPrimitive prim = obj.get("active").getAsJsonPrimitive();
if(prim.isBoolean()){
System.out.println("boolean");
}else{
System.out.println("number");
}
}
把它当作 “对象” .. – Meenal
可以选中这两个在if条件一样,好像(1 ||假){} –