简体   繁体   中英

Java GSON: Deserializing a field which has different types

I have ran into a problem with deserializing a json where there is a field that can have multiple types and that type is determined by another field.

To make this problem clear take the 3 examples below the json is called Extra and it has the field Unit which is always a string and it has the field Value which can be a decimal(example 1), an object(example 2) or a list of objects(example 3) depending on the value of the field Unit.

I am fairly new to GSON and not sure how to go about solving this, from looking at the API it seems i have to write a custom deserializer? How would i go about writing one for this example where the type of one field depends on another field?

Example 1
Extra {
Unit:"Decimal"
Value:0.0
}

Example 2
Extra {
Unit:"Object"
Value:{object}
}

Example 3
Extra {
Unit:"List of objects"
Value:[{object}
{object},
{object},
]
}

Try some thing like below: Take a bean eg: ExampleBean In ExampleBean take a propetry of another List of Your Values eg: List values;

And then try to convert GSON to List like below

public static List getListFromGsonString(String jsonString){
        Gson gson = new Gson();
        Type listType = new TypeToken() {}.getType();
        List list = (List)gson.fromJson(jsonString, listType);
        return list;
    }

This is what we have done in our project. Ignore if not applicable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM