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

Java使用改造使用GSON获取嵌套的JSON对象

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

Java使用改造使用GSON获取嵌套的JSON对象

你将编写一个自定义反序列化器,以返回嵌入式对象。

假设你的JSON是:

{    "status":"OK",    "reason":"some reason",    "content" :     {        "foo": 123,        "bar": "some value"    }}

然后,你将获得一个ContentPOJO:

class Content{    public int foo;    public String bar;}

然后编写一个反序列化器:

class MyDeserializer implements JsonDeserializer<Content>{    @Override    public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)        throws JsonParseException    {        // Get the "content" element from the parsed JSON        JsonElement content = je.getAsJsonObject().get("content");        // Deserialize it. You use a new instance of Gson to avoid infinite recursion        // to this deserializer        return new Gson().fromJson(content, Content.class);    }}

现在,如果你构造一个Gsonwith GsonBuilder并注册反序列化器:

Gson gson =     new GsonBuilder()        .registerTypeAdapter(Content.class, new MyDeserializer())        .create();

你可以将JSON直接反序列化为Content:

Content c = gson.fromJson(myJson, Content.class);

编辑以添加评论:

如果你有不同类型的消息,但是它们都有“ content”字段,则可以通过执行以下操作使Deserializer通用:

class MyDeserializer<T> implements JsonDeserializer<T>{    @Override    public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)        throws JsonParseException    {        // Get the "content" element from the parsed JSON        JsonElement content = je.getAsJsonObject().get("content");        // Deserialize it. You use a new instance of Gson to avoid infinite recursion        // to this deserializer        return new Gson().fromJson(content, type);    }}

你只需为每种类型注册一个实例:

Gson gson =     new GsonBuilder()        .registerTypeAdapter(Content.class, new MyDeserializer<Content>())        .registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>())        .create();

当你调用

.fromJson()
该类型时,该类型将携带到反序列化器中,因此它应适用于所有类型。

最后,在创建改造实例时:

Retrofit retrofit = new Retrofit.Builder()     .baseUrl(url)     .addConverterFactory(GsonConverterFactory.create(gson))     .build();


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

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

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