简体   繁体   English

转换列表<String>列出<Employee>或列表<MyCustomClass>

[英]Convert List<String> to List<Employee> or List<MyCustomClass>

I am getting a List as output from my database, which is like json array.我从我的数据库中得到一个 List 作为输出,它就像 json 数组。 I want to convert the same into List using java 8. I am trying to use the below code snippet but it gives me compilation error.我想使用 java 8 将其转换为 List。我正在尝试使用下面的代码片段,但它给了我编译错误。 Cannot convert from List to List无法从列表转换为列表

List<String> employeeList = getEmployeeList();
return (List<Employee>) employeeList;

Sample json array示例 json 数组

 {"employees":[    
        {"name":"Ram", "email":"ram@gmail.com", "age":23},    
        {"name":"Shyam", "email":"shyam23@gmail.com", "age":28},  
        {"name":"John", "email":"john@gmail.com", "age":33},    
        {"name":"Bob", "email":"bob32@gmail.com", "age":41}   
    ]} 

You can use the Jackson objectMapper to achieve that:您可以使用 Jackson objectMapper 来实现:

ObjectMapper mapper = new ObjectMapper();
List<Employee> employeeList = mapper.readValue(yourJsonString, new TypeReference<List<Employee>>(){});

Note that yourJsonString is your json data请注意, yourJsonString是您的 json 数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM