gpt4 book ai didi

java - Jackson JSON + Java 泛型获取 LinkedHashMap

转载 作者:IT老高 更新时间:2023-10-28 20:22:39 32 4
gpt4 key购买 nike

我有一个问题类似于 stackoverflow 上的一些问题,但没有一个真正回答我的问题。我使用 Jackson 的 ObjectMapper 并希望将此 JSON 字符串解析为用户对象列表:

[{ "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 列表,我使用泛型:

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;
}

但我得到的是 LinkedHashMapsList

我的代码有什么问题?

最佳答案

以下工作,根据 StaxMan 的建议,不再使用已弃用的静态 collectionType() 方法。

public class SoApp
{

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
System.out.println("Hello World!");

String s = "[{\"user\":\"TestCity\",\"role\":\"TestCountry\"},{\"user\":\"TestCity\",\"role\":\"TestCountry\"}]";
StringReader sr = new StringReader("{\"user\":\"TestCity\",\"role\":\"TestCountry\"}");
//UserRole user = mapper.readValue(sr, UserRole.class);

mapJsonToObjectList(s,UserRole.class);

}

protected static <T> List<T> mapJsonToObjectList(String json, Class<T> clazz) throws Exception
{
List<T> list;
ObjectMapper mapper = new ObjectMapper();
System.out.println(json);
TypeFactory t = TypeFactory.defaultInstance();
list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz));

System.out.println(list);
System.out.println(list.get(0).getClass());
return list;
}
}

...

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;
}

@Override
public String toString()
{
return "UserRole [user=" + user + ", role=" + role + "]";
}

}

输出...

 Hello World!
[{"user":"TestCity","role":"TestCountry"},{"user":"TestCity","role":"TestCountry"}]
[UserRole [user=TestCity, role=TestCountry], UserRole [user=TestCity, role=TestCountry]]
class com.test.so.fix.UserRole

关于java - Jackson JSON + Java 泛型获取 LinkedHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7040279/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com