如何将LinkedHashMap转换为自定义java对象? [英] how to convert LinkedHashMap to Custom java object?
问题描述
我正在尝试通过RESTful WS将数据从一个应用程序转移到另一个应用程序并且它可以工作,但我无法使用此数据,因为我无法转换它... WS返回一个像这样的对象列表:
I'm trying to get the data from one app to another via RESTful WS and it works, but I cannot use this data since I cannot cast it... WS returns a List of objects like this:
{id=1, forename=John, surname=Bloggs, username=jbloggs, role=Graduate Developer, office=London, skills=[{technology=Java, experience=2.5}, {technology=Web, experience=2.0}, {technology=iOS, experience=0.0}, {technology=.NET, experience=0.0}]}
让我使用Jackson的ObjectMapper:
to get I it use Jackson's ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
List<ConsultantDto> list = new ArrayList<ConsultantDto>();
try {
list = mapper.readValue(con.getInputStream(), ArrayList.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
之后我有3行代码:
System.out.println(list.get(0));
System.out.println(list.get(0).getForename());
return list;
返回,因为此方法的返回值被传递给在浏览器中显示正确数据的其他Web服务。有趣的事情发生在两条印刷线上,一条打印出来自这篇文章顶部的数据({id:1 ...}),另一条则抛出异常:
return because this method's return value is passed to other webservice which displays correct data in a browser. Interesting thing happens with two printing lines, one prints the data from the top of this post ({id:1 ... }) but the other one throws exception:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.xxx.web.dto.rp.ConsultantDto
ConsultantDto和SkillDto是两个合法的类,它们的所有属性都设置为与来自WS的数据相匹配,所有的getter / setter都已到位。就我而言,LinkedHashMap将东西存储为键:值对,所以我只是看不出这个异常的来源。我如何解决它,为什么ObjectMapper只是正确解析值(当我得到一个ConsultantDto而不是List时它会这样做?)
ConsultantDto and SkillDto are two legit classes which have all properties set to match the data from WS, all getters/setters are in place. As far as I'm concerned LinkedHashMap stores stuff as key:value pairs, so I just don't see where is this exception coming from. How can I fix it and why doesn't ObjectMapper just parse the value correctly (which it does when I get a single ConsultantDto rather than a List)?
推荐答案
您需要这样做:
List<ConsultantDto> myObjects =
mapper.readValue(jsonInput, new TypeReference<List<ConsultantDto>>(){});
(来自 SO回答)
你必须使用<$的原因c $ c> TypeReference 是因为Java的一个不幸的怪癖。如果Java有一个合适的泛型,我敢打赌你的语法会有效。
The reason you have to use TypeReference
is because of an unfortunate quirk of Java. If Java had a proper generics, I bet your syntax would have worked.
这篇关于如何将LinkedHashMap转换为自定义java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!