简体   繁体   English

Java GSON:反序列化具有不同类型的字段

[英]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. 我遇到了反序列化json的问题,其中存在一个字段可以具有多种类型,而该类型由另一个字段确定。

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. 为了使这个问题更清楚,请在json下面的3个示例中将其称为Extra,它的字段Unit始终是字符串,字段Value可以是十进制(示例1),对象(示例2)或对象列表(示例3)取决于字段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? 我对GSON相当陌生,不确定如何解决此问题,从看API来看,我似乎必须编写一个自定义解串器? 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; 尝试以下类似的操作:以一个bean为例:ExampleBean在ExampleBean中,继承另一个您的值列表,例如:列表值;

And then try to convert GSON to List like below 然后尝试将GSON转换为List,如下所示

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. 如果不适用,请忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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