Jackson JSON + Java Generics get LinkedHashMap

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

[{ "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;
}

但是我得到的是.ListLinkedHashMaps

我的代码有什么问题?


答案 1

以下工作,并且根据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

答案 2

推荐