Gson-相同的字段名称,不同的类型
我今天在另一个问题中提出了这个问题,但是
由于措辞的方式,恐怕无法解决任何问题。
我有一个json输入,其中包含以下数据:
杰森
如您所见,option_value项是一个对象中的Array和
另一个对象中的简单字符串。
我怎样才能让Gson正确处理呢?我的类将此描述为
List对象,因此它适用于option_value是
数组的前几个项目,但是当它成为字符串时,应用程序崩溃,并且我收到json
parse异常。
有没有解决方法?
更新
根据要求添加班级的相关部分:
public class Options    {
        String product_option_id;
        String option_id;
        String name;
        String type;
        String required;
        List<OptionValue> option_value;
        // 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 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);以上是 Gson-相同的字段名称,不同的类型 的全部内容, 来源链接: utcz.com/qa/422346.html

