Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

增加泛型, 支持 RestTemplate Jackson 正确解析 #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

XiaoZiShan
Copy link

@see RestTemplate getForObject 方法获取List,Map 对象时 返回错误的LinkedHashMap
注意 jackson只知道您想要一个List,但对类型没有任何限制。
默认情况下,Jackson将JSON对象反序列化为LinkedHashMap,因此这就是为什么要获取的原因ClassCastException。
(必须用exchange 方法 + ParameterizedTypeReference + 映射类泛型化 指定泛型进行调用)
https://stackoverflow.com/questions/19463372
https://www.cnblogs.com/silentdoer/p/9012599.html

@see RestTemplate getForObject 方法获取List,Map 对象时 返回错误的LinkedHashMap
      注意 jackson只知道您想要一个List,但对类型没有任何限制。
      默认情况下,Jackson将JSON对象反序列化为LinkedHashMap,因此这就是为什么要获取的原因ClassCastException。
     (必须用exchange 方法 + ParameterizedTypeReference + 映射类泛型化 指定泛型进行调用)
     https://stackoverflow.com/questions/19463372
     https://www.cnblogs.com/silentdoer/p/9012599.html
@XiaoZiShan
Copy link
Author

错误例子 (泛型部对象被反序列化为由 LinkedHashMap 组成的 K/V)

ResultObject result = restTemplate.getForObject(new URI(URLConstant.QUERY_ALL_LIST_URL), ResultObject.class );

正确例子 (泛型识别正确)

ParameterizedTypeReference<ResultObject<Map<String, List<XXXResponseVO>>>> typeRef = new ParameterizedTypeReference<ResultObject<Map<String, List<XXXResponseVO>>>>() {}; 
ResultObject<Map<String, List<XXXResponseVO>>> result = restTemplate.exchange(new URI(QUERY_ALL_LIST_URL), HttpMethod.GET, null, typeRef).getBody();

@XiaoZiShan XiaoZiShan changed the title 增加泛型, 支持 RestTemplate Jackson 解析正确 增加泛型, 支持 RestTemplate Jackson 正确解析 Mar 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant