Gson - Same field name, different types

Asim

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 data:

Json

As you can see, the option_value item is an Array in one object and a simple string in another object.

How can I make Gson handle this properly? My class has this described as a List object, so it works for the first few items where option_value is an array, but when it becomes a string, the app crashes and I get a json parse exception.

Is there a workaround for this?

UPDATE

Adding the relevant part of my class as requested:

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
        }
    }
Denys Vasylenko

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<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);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to handle different data types with same attribute name with Gson?

From Java

Json schema with anyOf field with same name and different types to POJO + Jackson

From Dev

gson read same field with different structure

From Dev

XSD different types same name

From Dev

ElasticSearch - searching different doc_types with the same field name but different analyzers

From Dev

Field names with the same name across types having different index/type in Elasticsearch

From Dev

Elasticsearch mapping - different data types in same field

From Dev

Interface with members with same name and different return types

From Dev

XSD multiple elements with same name but different types

From Dev

Deserializing attributes of same name but different types in Jackson?

From Dev

Deserializing attributes of same name but different types in Jackson?

From Dev

XSD multiple elements with same name but different types

From Dev

parsing json using Gson which has objects with same field name

From Dev

Gson deserialize field to variable with different name although having variable with the field name

From Dev

Gson deserializing with changing field types

From Dev

Gson deserialization with changing field types

From Dev

How to query two types with same field name ElasticSearch with Java code

From Java

Powershell Script to move different file types with the same name to share folder

From Java

Using ModelMapper on different data types with same attribute name

From Dev

Is it legal to define two methods with the same name but different returning types?

From Dev

multiple functions with same name but different argument types as template parameter

From Dev

XMLArray with different types but same element name and i:type attribute

From Dev

Putting interface behind properties with same name but different types

From Dev

Java Templates, how to use two classes with the same name and different types

From Dev

java take different list types with same method name

From Dev

Is it possible to extract same field with two different name through regex?

From Dev

Different types of the same object

From Dev

GSON - How can I parse two JSONArrays with the same name, but different parameters?

From Dev

Java - Two methods with same name, same argument of different type, but the types are related hierarchically

Related Related

  1. 1

    How to handle different data types with same attribute name with Gson?

  2. 2

    Json schema with anyOf field with same name and different types to POJO + Jackson

  3. 3

    gson read same field with different structure

  4. 4

    XSD different types same name

  5. 5

    ElasticSearch - searching different doc_types with the same field name but different analyzers

  6. 6

    Field names with the same name across types having different index/type in Elasticsearch

  7. 7

    Elasticsearch mapping - different data types in same field

  8. 8

    Interface with members with same name and different return types

  9. 9

    XSD multiple elements with same name but different types

  10. 10

    Deserializing attributes of same name but different types in Jackson?

  11. 11

    Deserializing attributes of same name but different types in Jackson?

  12. 12

    XSD multiple elements with same name but different types

  13. 13

    parsing json using Gson which has objects with same field name

  14. 14

    Gson deserialize field to variable with different name although having variable with the field name

  15. 15

    Gson deserializing with changing field types

  16. 16

    Gson deserialization with changing field types

  17. 17

    How to query two types with same field name ElasticSearch with Java code

  18. 18

    Powershell Script to move different file types with the same name to share folder

  19. 19

    Using ModelMapper on different data types with same attribute name

  20. 20

    Is it legal to define two methods with the same name but different returning types?

  21. 21

    multiple functions with same name but different argument types as template parameter

  22. 22

    XMLArray with different types but same element name and i:type attribute

  23. 23

    Putting interface behind properties with same name but different types

  24. 24

    Java Templates, how to use two classes with the same name and different types

  25. 25

    java take different list types with same method name

  26. 26

    Is it possible to extract same field with two different name through regex?

  27. 27

    Different types of the same object

  28. 28

    GSON - How can I parse two JSONArrays with the same name, but different parameters?

  29. 29

    Java - Two methods with same name, same argument of different type, but the types are related hierarchically

HotTag

Archive