栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在反序列化JSON响应中使用Gson处理NumberFormatException

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在反序列化JSON响应中使用Gson处理NumberFormatException

最初,我尝试为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);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号