我想创建一个使用具有动态类型的参数的 API 端点。
收到的 JSON 参数可能类似于以下任一形式:
{
entityType: "A",
createList:[
{row: 1, name: "sted", department:"drulp"},
{row: 2, name: "mary", department:"kko"},
],
updateList:[
{row: 3, name: "sddf", department:"fff"},
{row: 4, name: "few", department:"kko"},
]
}
{
entityType: "B",
createList:[
{firstName: "John", phone: "0412345678", country:"USA"},
{firstName: "Mary", phone: "0412247474", country:"CANADA"},
],
updateList:[
{firstName: "Tim", phone: "0412345678", country:"Australia"},
{firstName: "Luke", phone: "042728282", country:"CANADA"},
]
}
从上面的例子中,我们可以看到不同的
entityType
可能有不同类型的createList
和updateList
。
现在我正在创建一个 api 端点来接收这些 Json 数据。我的代码如下:
控制器
@RequestMapping(method = RequestMethod.POST, value = "/import")
public void executeImport(@RequestBody ImportRequest<? extends ImportModel> request) {
// some codes...
}
ImportRequest
班:
public class ImportRequest<T extends ImportModel> {
private String entityType;
private List<T> createList;
private List<T> updateList;
ImportModel
班:
public abstract class ImportModel {
}
ImportTypeAModel
班:
public class ImportTypeAModel extends ImportModel {
private Integer row;
private String name;
private String department;
// Getters and Setters
}
ImportTypeBModel
班:
public class ImportTypeBModel extends ImportModel {
private String firstName;
private String phone;
private String country;
// Getters and Setters
}
但是,当我调用API时,它显示以下消息:
Cannot construct instance of `com.core.domain.ImportModel` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (PushbackInputStream); line: 1, column: 44] (through reference chain: com.core.domain.ImportRequest["createList"]->java.util.ArrayList[0])
如何创建端点来使用这些动态类型参数?
一些注释包括每种类型的自定义控制器、自定义序列化器/反序列化器等。这些都不需要。如果您使用映射对您的类进行建模,Spring 就支持这种开箱即用的方式。 createList 等只是一个
ArrayList<LinkedHashMap<String, String>>
。
然后你将拥有一切作为通用键/值对。