杰克逊·JSON + Java泛型获取LinkedHashMap
我有一个问题类似于 stackoverflow 上的一些问题,但没有一个真正回答我的问题。我使用 Jackson 的 ObjectMapper
并希望将此 JSON 字符串解析为 User 对象列表:
[{ "user" : "Tom", "role" : "READER" },
{ "user" : "Agnes", "role" : "MEMBER" }]
我定义一个如下内部类:
public class UserRole {
private String user
private String role;
public void setUser(String user) {
this.user = user;
}
public void setRole(String role) {
this.role = role;
}
public String getUser() {
return user;
}
public String getRole() {
return role;
}
}
将 JSON 字符串解析为 UserRoles
列表code> 我使用泛型:
protected <T> List<T> mapJsonToObjectList(String json) throws Exception {
List<T> list;
try {
list = mapper.readValue(json, new TypeReference<List<T>>() {});
} catch (Exception e) {
throw new Exception("was not able to parse json");
}
return list;
}
但我得到的是 LinkedHashMaps
的 List
。
我的代码有什么问题吗?
I have a question which is similar to some questions at stackoverflow but none really answer my problem. I use the ObjectMapper
of Jackson and want to parse this JSON string into an List of User objects:
[{ "user" : "Tom", "role" : "READER" },
{ "user" : "Agnes", "role" : "MEMBER" }]
I define an inner class like this:
public class UserRole {
private String user
private String role;
public void setUser(String user) {
this.user = user;
}
public void setRole(String role) {
this.role = role;
}
public String getUser() {
return user;
}
public String getRole() {
return role;
}
}
To parse the JSON String to an List of UserRoles
I use generics:
protected <T> List<T> mapJsonToObjectList(String json) throws Exception {
List<T> list;
try {
list = mapper.readValue(json, new TypeReference<List<T>>() {});
} catch (Exception e) {
throw new Exception("was not able to parse json");
}
return list;
}
But what I get back is a List
of LinkedHashMaps
.
What is wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下工作有效,并且根据 StaxMan 的建议,不再使用已弃用的静态
collectionType()
方法。...
输出...
The following works and as per StaxMan's advice no longer uses the deprecated static
collectionType()
method....
output...