杰克逊将JSON反序列化为多个POJO

时间:2012-08-21 12:35:26

标签: android json spring jackson

您好,我有以下JSON

{
 "code": 0,
 "response": {
  "userObject": {
   "User": {
    "id": "355660",
    "first_name": "Dummy",
    "last_name": "dummy",
    "email": "dumb@email.com",
    "birthday": "2012-05-07",
    "created": "2012-08-21 06:41:05",
    "modified": "2012-08-21 06:41:05",
    "image_url": null,
   },
   "Location": {
    "id": "273550",
    "name": "New York City",
    "asciiName": "New York City",
    "lat": "40.714272",
    "lon": "-74.005966",
    "geoname_modified": "2011-11-08 00:00:00",
    "timeZone": "America/New_York",
    "countryName": "United States",
    "state": "New York",
    "created": "2012-07-12 12:11:01",
    "modified": "2012-08-20 14:27:24"
   }
  }
 }
}

我有两个课程,分别为 Location User

我知道如果我创建像

这样的嵌套类,我可以获取对象
    response
     ->UserObject
         *User
         *Location

但我不想为 UserObject response创建两个额外的类,只是为了包装两个POJO。 有没有更简单的方法呢?

我将Jackson Parser Spring for android

一起使用

2 个答案:

答案 0 :(得分:4)

如果你真的想避免丢弃类,可以分两步完成,例如:

JsonNode tree = mapper.readTree(...);
User user = mapper.treeToValue(tree.path("response").path("userObject").get("User"), User.class);
Location loc = mapper.convertValue(tree.path("response").path("userObject").get("Location"), Location.class);

但是,我可能会选择使用愚蠢的struct-classes:

static class Response {
  public UserObject userObject;
}
static class UserObject {
  public Location Location;
  public User User;
}

因为它的代码真的不多。

答案 1 :(得分:2)

您可以创建classes或使用arrays,而不是创建hashmap。就个人而言,我只想创建classes。我认为这可以让您在应用程序中获得更大的灵活性,并且可以让您轻松处理对象。我知道设置它们需要时间,但是一旦你这样做,你可以使用ArrayList,你可以更轻松地解析JSON