Java ClassCastException:RestTemplate 返回 List<LinkedHashMap> 而不是 List<MymodelClass>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19463372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:29:30  来源:igfitidea点击:

ClassCastException: RestTemplate returning List<LinkedHashMap> instead of List<MymodelClass>

javaandroidspringclasscastexceptionresttemplate

提问by Erick

I'm trying to access getter methods on my MyModelClass but my code is returning List<LinkedHashMap>instead of List<MyModelClass>. This is my code.

我正在尝试访问 MyModelClass 上的 getter 方法,但我的代码返回List<LinkedHashMap>而不是List<MyModelClass>. 这是我的代码。

List<MyModelClass> myModelClass=(List<MyModelClass>) restTemplate.postForObject(url,mvm,List.class);

System.out.println("Response= " +  myModelClass);

I tried to print the response and I got the JSON Response that I'm expecting. but when I tried to run this code.

我尝试打印响应,但得到了我期望的 JSON 响应。但是当我尝试运行此代码时。

System.out.println("Response= " +  myModelClass.get(0).getMessage());

It will produce this error.

它会产生这个错误。

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.XXX.XXX.MyModelClass 

It is a mismatch. Can someone help me to get rid with this error? thanks.

这是一个不匹配。有人可以帮我摆脱这个错误吗?谢谢。

MyModelClass

我的模型类

public class MyModelClass{

    /**
     * 
     */
    @JsonProperty("id")
    public String id;

    @JsonProperty("type")
    public String type;

    @JsonProperty("user")
    public String user;

    @JsonProperty("message")
    public String message;

    //getters

Error for

错误为

MyModelClass[] myModelClass= restTemplate.postForObject(url,mvm, myModelClass[].class);

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

org.springframework.http.converter.HttpMessageNotReadableException:无法读取 JSON:无法从 START_OBJECT 令牌中反序列化 java.util.ArrayList 的实例

JSON Response Structure

JSON 响应结构

    [{"key1":"value1","key2":"value2","parameters":{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"}},
{"key12":"value12","key22":"value22","parameters":{"key12":"value12","key22":"value22","key32":"value32","key42":"value42","key52":"value52"}}]

If there is any suggestion on how to map this kind of JSON Response in RestTemplate,It would help a lot. thanks

如果有关于如何在 RestTemplate 中映射这种 JSON 响应的任何建议,这将有很大帮助。谢谢

回答by Sotirios Delimanolis

With the following method call

使用以下方法调用

List<MyModelClass> myModelClass=(List<MyModelClass>) restTemplate.postForObject(url,mvm,List.class);

All Hymanson knows is that you want a List, but doesn't have any restriction on the type. By default Hymanson deserializes a JSON object into a LinkedHashMap, so that's why you are getting the ClassCastException.

Hymanson 只知道你想要一个List,但对类型没有任何限制。默认情况下,Hymanson 将 JSON 对象反序列化为LinkedHashMap,因此这就是您获得ClassCastException.

If your returned JSON is an array, one way to get it is to use an array

如果您返回的 JSON 是一个数组,则获取它的一种方法是使用数组

MyModelClass[] myModelClasses = restTemplate.postForObject(url,mvm, MyModelClass[].class);

You can always add the elements from that array to a List.

您始终可以将该数组中的元素添加到List.

I can't remember since what version, but RestTemplate#exchangenow has an overload that accepts a ParameterizedTypeReferenceargument. The ParameterizedTypeReferenceis the type token hack for suggesting a parameterized type as the target for deserialization.

我不记得从哪个版本开始,但RestTemplate#exchange现在有一个接受ParameterizedTypeReference参数的重载。这ParameterizedTypeReference是用于建议参数化类型作为反序列化目标的类型标记黑客。

You can refactor the code above to use exchangeinstead of postForObject, and use ParameterizedTypeReferenceto get a List<MyModelClass>. For example

您可以重构上面的代码以使用exchange而不是postForObject, 并使用ParameterizedTypeReference来获取List<MyModelClass>. 例如

ParameterizedTypeReference<List<MyModelClass>> typeRef = new ParameterizedTypeReference<List<MyModelClass>>() {
};
ResponseEntity<List<MyModelClass>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(mvm), typeRef);
List<MyModelClass> myModelClasses = responseEntity.getBody();