使用jackson API将json数组字符串转换为java对象

时间:2016-12-06 07:26:08

标签: java jackson

我有类似下面的JSON字符串,并希望使用jackson API转换为Java对象。

 [
      {
        "Users": {
          "id": "1",
          "userId": "1424",
          "Firstname": "lms",

        }
      },
      {
        "Users": {
          "id": "2",
          "userId": "4527",
          "Firstname": "Matthew",
         }
      }
 ]

你能帮帮我吗。

2 个答案:

答案 0 :(得分:0)

这是解决方案,就像魅力一样:

try {
                TypeFactory typeFactory = mapper.getTypeFactory();
                CollectionType collectionType = typeFactory.constructCollectionType(
                                                    List.class, Users.class);
                List<Users> usersList =  mapper.readValue(new File("list.json"), collectionType);     

            } catch (IOException e) {
                e.printStackTrace();
            }

答案 1 :(得分:-1)

Google是您的朋友,此example显示了一个很好的演示

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);