我在使用Gson反序列化json字符串時遇到問題。我收到一系列命令。該命令可以是start,stop或其他類型的命令。我自然具有多態(tài)性,并且start / stop命令從command繼承。如何使用gson將其序列化回正確的命令對象?似乎我只獲得基本類型,即聲明的類型,而從未獲得運行時類型。
3 回答

汪汪一只貓
TA貢獻1898條經(jīng)驗 獲得超8個贊
為了擴展他的示例,可以通過以下更改使他的適配器類通用以適用于所有類型的對象(不僅僅是IAnimal):
class InheritanceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T>
{
....
? ? public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context)
....
? ? public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
....
}
在測試類中:
public class Test {
? ? public static void main(String[] args) {
? ? ? ? ....
? ? ? ? ? ? builder.registerTypeAdapter(IAnimal.class, new InheritanceAdapter<IAnimal>());
? ? ? ? ....
}
添加回答
舉報
0/150
提交
取消