Gson - Same field name, different types

前端 未结 2 593
名媛妹妹
名媛妹妹 2020-12-04 22:28

I asked this in a different question today but I\'m afraid that won\'t get any solution because of how it was phrased.

I have a json input that has the following dat

2条回答
  •  暖寄归人
    2020-12-04 22:57

    I have a solution for you :) For this purpose we should use custom deserializer. Remake your class like this:

    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 mOptionValue;
    
        //setter
        public void setOptionValues(List 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 {
    
        @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 values = new Gson().fromJson(valuesString, new TypeToken>() {}.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);
    

提交回复
热议问题