本文介绍了我可以实例化一个超类,并根据提供的参数来实例化一个特定的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我使用Google的GSON套件 http://code.google.com/p/google -gson / I am using Google's GSON package http://code.google.com/p/google-gson/我将JSON转换为Java。I am converting JSON to Java.我有这段代码在这里我做了转换。I have this fragment of code where I do the conversion.Gson gson = new Gson();Type collectionType = new TypeToken<Collection<QueryProperty>>() {}.getType();Collection<QueryProperty> queryProperties = gson.fromJson(query, collectionType);我的QueryProperty类有这些字段(带getters / setters): My QueryProperty class has these fields (with getters/setters):int id;String uri;String name;Set<QueryValue> values;String selected; QueryValue类具有以下字段(与getter / setter):The QueryValue class had these fields (with getters/setters) perviously:int id;String uri;String name;我现在希望能有不同的类型 QueryValue。I now want to be able to have different types of QueryValue.我想添加一个NumericQueryValue类(QueryValue的子类),所以我可以传入一组用于查询db的边界。 / p> I want to add a NumericQueryValue class (subclass of QueryValue), so I can pass in a set of bounds with which to query the db.double lower;double upper;并且想要创建一个与QueryValue相同的新ResourceQueryValue(QueryValue的子类): And want to make a new ResourceQueryValue (subclass of QueryValue) which looks the same as QueryValue used to:int id;String uri;String name;无论如何,我可以让这项工作成功。这是一个通用的QueryValue类,但根据JSON提供的参数返回正确的子类。Is there anyway I can make this work. That is have a generic QueryValue class, but have the correct subclass returned depending on the parameters that the JSON supplies.如果我不清楚,请告诉我。 If I have not been clear please do let me know.推荐答案除了实现自定义的反序列化处理,Gson目前还没有一种简单的多态反序列化机制。下一个版本看起来像它将提供一个内置的解决方案。Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.前一个StackOverflow.com问题和答案(一些例子)关于此主题:Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic: 反序列化带有未知编译时类型的泛型,其中一个字段指示类型 为GSON字段解析JSON,没有特定结构 > 使用google gson进行json对象序列化/反序列化 gson多态性 Deserialising a generic with unknown compile time type where a field indicates the typeParse JSON with no specific structure for a field with GSONjson object serialization/deserialization using google gsonPolymorphism with gson 这篇关于我可以实例化一个超类,并根据提供的参数来实例化一个特定的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 09:38