最初,我尝试为Integer值编写一个通用的自定义类型适配器,以捕获
NumberFormatException和返回0,但Gson不允许基本类型的TypeAdaptors:
java.lang.IllegalArgumentException: Cannot register type adapters for class java.lang.Integer
之后,我
FooRuntime为该
runtime字段引入了一个新的Type ,因此
Foo该类现在如下所示:
public class Foo{ private String name; private FooRuntime runtime; public int getRuntime() { return runtime.getValue(); }}public class FooRuntime{ private int value; public FooRuntime(int runtime) { this.value = runtime; } public int getValue() { return value; }}类型适配器处理自定义反序列化过程:
public class FooRuntimeTypeAdapter implements JsonDeserializer<FooRuntime>, JsonSerializer<FooRuntime>{ public FooRuntime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { int runtime; try { runtime = json.getAsInt(); } catch (NumberFormatException e) { runtime = 0; } return new FooRuntime(runtime); } public JsonElement serialize(FooRuntime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getValue()); }}现在必须使用
GsonBuilder注册类型适配器,因此将空字符串解释为0而不是抛出
NumberFormatException。
String input = "{n" + " "name" : "Test",n" + " "runtime" : ""n" + "}";GsonBuilder builder = new GsonBuilder();builder.registerTypeAdapter(FooRuntime.class, new FooRuntimeTypeAdapter());Gson gson = builder.create();Foo foo = gson.fromJson(input, Foo.class);


