如何将 LinkedHashMap 转换为自定义 java 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22358872/
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-13 15:13:46  来源:igfitidea点击:

how to convert LinkedHashMap to Custom java object?

javajsonweb-services

提问by Lucas

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:

我正在尝试通过 RESTful WS 将数据从一个应用程序获取到另一个应用程序并且它可以工作,但是我无法使用此数据,因为我无法投射它...... WS 返回一个对象列表,如下所示:

{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}]}

to get I it use Hymanson's ObjectMapper:

为了让我使用 Hymanson 的 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();

    }

after that I have 3 lines of code:

之后我有3行代码:

System.out.println(list.get(0));
System.out.println(list.get(0).getForename());
return list;

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:

返回,因为此方法的返回值被传递给在浏览器中显示正确数据的其他 web 服务。有趣的事情发生在两条打印行上,一条从这篇文章的顶部 ({id:1 ... }) 打印数据,但另一条抛出异常:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.xxx.web.dto.rp.ConsultantDto

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)?

ConsultantDto 和 SkillDto 是两个合法的类,它们的所有属性都设置为匹配来自 WS 的数据,所有 getter/setter 都已就位。就我而言,LinkedHashMap 将东西存储为键:值对,所以我只是不知道这个异常来自哪里。我该如何修复它,为什么 ObjectMapper 不正确解析值(当我得到一个 ConsultantDto 而不是 List 时它会这样做)?

采纳答案by Enno Shioji

You need to do this:

你需要这样做:

List<ConsultantDto> myObjects =
    mapper.readValue(jsonInput, new TypeReference<List<ConsultantDto>>(){});

(From this SO answer)

(来自这个SO 答案

The reason you have to use TypeReferenceis because of an unfortunate quirk of Java. If Java had a proper generics, I bet your syntax would have worked.

您必须使用的原因TypeReference是 Java 的一个不幸的怪癖。如果 Java 有合适的泛型,我敢打赌你的语法会奏效。

回答by Donald Choi

import:

进口:

import com.fasterxml.Hymanson.databind.ObjectMapper;

object:

目的:

private ObjectMapper mapper = new ObjectMapper();

examples:

例子:

PremierDriverInfoVariationDTO premierDriverInfoDTO = 
mapper.convertValue(json, PremierDriverInfoVariationDTO.class); 
log.debug("premierDriverInfoDTO : {}", premierDriverInfoDTO);

or

或者

Map<String, Boolean> map = mapper.convertValue(json, Map.class);
log.debug("result : {}", map);
assertFalse(map.get("eligiblePDJob"));