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

Gson自定义脱盐器,用于对象中的一个变量

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

Gson自定义脱盐器,用于对象中的一个变量

您需要为该

Apple
类型注册一个自定义类型适配器。在类型适配器中,您将添加逻辑以确定是否为您提供了数组或单个对象。使用该信息,您可以创建
Apple
对象。

除以下代码外,请修改您的Apple模型对象,以使该

seeds
字段不会自动解析。将变量声明更改为类似以下内容:

private List<Seed> seeds_funkyName;

这是代码:

GsonBuilder b = new GsonBuilder();b.registerTypeAdapter(Apple.class, new JsonDeserializer<Apple>() {    @Override    public Apple deserialize(JsonElement arg0, Type arg1,        JsonDeserializationContext arg2) throws JsonParseException {        JsonObject appleObj = arg0.getAsJsonObject();        Gson g = new Gson();        // Construct an apple (this shouldn't try to parse the seeds stuff        Apple a = g.fromJson(arg0, Apple.class);        List<Seed> seeds = null;        // Check to see if we were given a list or a single seed        if (appleObj.get("seeds").isJsonArray()) { // if it's a list, just parse that from the JSON seeds = g.fromJson(appleObj.get("seeds"),         new TypeToken<List<Seed>>() {         }.getType());        } else { // otherwise, parse the single seed, // and add it to the list Seed single = g.fromJson(appleObj.get("seeds"), Seed.class); seeds = new ArrayList<Seed>(); seeds.add(single);        }        // set the correct seed list        a.setSeeds(seeds);        return a;    }});

有关更多信息,请参阅Gson指南。



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

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

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