我正在处理一个API,它返回整数(1 = true,other = false)来表示布尔值.
我已经看到了这个问题和答案,但我需要能够指定应该应用哪个字段,因为有时整数实际上是一个整数.
编辑:传入的JSON可能看起来像这样(也可能是String而不是int等...):
{
"regular_int": 1234,
"int_that_should_be_a_boolean": 1
}
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来指定int_that_should_be_a_boolean应该解析为布尔值,并regular_int应解析为整数.
Mah*_*ade 25
我们将为Gson提供一个小钩子,一个用于布尔值的自定义解串器,即一个实现JsonDeserializer<Boolean>接口的类:
CustomBooleanTypeAdapter
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
{
int code = json.getAsInt();
return code == 0 ? false :
code == 1 ? true :
null;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它,我们需要改变一点我们获取Gsonmapper实例的方式,使用工厂对象GsonBuilder,这是一种常用的模式方法GSON.
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();
Run Code Online (Sandbox Code Playgroud)
对于原始类型使用低于一
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();
Run Code Online (Sandbox Code Playgroud)
享受JSON解析!
| 归档时间: |
|
| 查看次数: |
7544 次 |
| 最近记录: |