32

我有一个问题类似于 stackoverflow 上的一些问题,但没有一个真正回答我的问题。我使用ObjectMapperJackson 并希望将此 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;
}

但我得到的是一个ListLinkedHashMaps

我的代码有什么问题?

4

1 回答 1

39

以下工作并且根据 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
于 2011-08-12T15:40:55.087 回答