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

Gson-相同的字段名称,不同的类型

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

Gson-相同的字段名称,不同的类型

我为您提供解决方案:)为此,我们应该使用自定义
解串器。重新制作您的课程,如下所示:

public class Options{    @SerializedName ("product_option_id");    String mProductOptionId;    @SerializedName ("option_id");    String mOptionId;    @SerializedName ("name");    String mName;    @SerializedName ("type");    String mType;    @SerializedName ("required");    String mRequired;    //don't assign any serialized name, this field will be parsed manually    List<OptionValue> mOptionValue;    //setter    public void setOptionValues(List<OptionValue> optionValues){         mOptionValue = optionValues;    }    // get set stuff here    public class OptionValue    {        String product_option_value_id;        String option_value_id;        String name;        String image;        String price;        String price_prefix;        // get set stuff here    }public static class OptionsDeserilizer implements JsonDeserializer<Options> {    @Override    public Offer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {        Options options = new Gson().fromJson(json, Options.class);        JsonObject jsonObject = json.getAsJsonObject();        if (jsonObject.has("option_value")) { JsonElement elem = jsonObject.get("option_value"); if (elem != null && !elem.isJsonNull()) {        String valuesString = elem.getAsString();      if (!TextUtils.isEmpty(valuesString)){          List<OptionValue> values = new Gson().fromJson(valuesString, new TypeToken<ArrayList<OptionValue>>() {}.getType());          options.setOptionValues(values);      } }        }        return options ;    }}}

Before we can let gson parse json, we should register our custom deserializer:

Gson gson = new GsonBuilder()    .registerTypeAdapter(Options.class, new Options.OptionsDeserilizer())     .create();

And now - just call:

Options options = gson.fromJson(json, Options.class);


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

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

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