泛型创建实例usinc jackson时,如何在Java中传递方法参数中类的类型信息?
我有一个http端点,它返回不同类型的json,比如汽车、自行车、卡车。 JSON的结构如下所示,每个类都非常相似
{
"Rows": [
{
"key1": "val1",
"key2": "val2",
}
]
}
我想编写一个基于类型参数创建列表对象(Car、Bike、Truck)的通用方法(我已经使用适当的jackson绑定创建了所有pojo,它们扩展了Vehicle类)
我提出了以下内容,但它在运行时抛出异常
static <T extends Vehicle> List<T> getTiles(String vehicleName, Class<T> concreteClass) throws IOException {
Map<String, String> queryParamMap = new HashMap<>();
queryParamMap.put("apiKey", "<KEY>");
queryParamMap.put("type", vehicleName);
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder builder = new HttpUrl.Builder()
.scheme("https")
.host("<URL>")
.addPathSegment("1");
queryParamMap.entrySet().stream().forEach(k -> builder.addQueryParameter(k.getKey(), k.getValue()));
HttpUrl url = builder.build();
Request request = new Request.Builder()
.addHeader("accept", "application/json")
.url(url).build();
Response response = client.newCall(request).execute();
Map<String, List<T>> m = mapper.readValue(response.body().string(),
new TypeReference<Map<String, List<T>>>() {
});
return m.get("Rows");
}
我把它叫做
List<Car> cars = Utils.getTiles("CAR", Car.class);
我得到以下例外
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.models.Vehicle` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
我知道这与类型擦除有关,因为在运行时T绑定到车辆而不是汽车
我如何解决这个问题
共 (0) 个答案