[英]Gson: handle json object field that can return different primitive types?
An API my application is communicating with sends responses that look like this: 我的应用程序正在与之通信的API发送如下响应:
{
id:12345,
active:1
}
The problem is that older versions of the API sends the response field as a boolean value rather than an int like so 问题在于,较旧版本的API将响应字段作为布尔值而不是像这样的int发送
{
id:12345,
active:false,
}
With Gson, how can I handle both with no knowledge of which version will be returned? 使用Gson,我如何在不知道将返回哪个版本的情况下处理这两个问题?
Register a CustomDeserializer for boolean and when ever a boolean is encountered inside any object, gson will try to deserialize with the rules that you defined. 为布尔值注册一个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());
}
Output: 输出:
true
false
false
true
PFB the way to handle this. 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.