0

こんにちは私は次の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"
   }
  }
 }
}

と にそれぞれ 1 つずつ、2 つのクラスが Location あります。 User

次のようなネストされたクラスを作成すると、オブジェクトを取得できることがわかります

    response
     ->UserObject
         *User
         *Location

しかし、2 つの POJO をラップするためだけに2 つの余分なクラス UserObject を作成したくありません。 responseそれを行う簡単な方法はありますか??

で使用Jackson Parser していますSpring for android

4

2 に答える 2

4

使い捨てクラスを本当に避けたい場合は、次のように 2 つのステップで行うこともできます。

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

しかし、ええ、代わりに愚かな構造体クラスを使うかもしれません:

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

それは実際にはそれほど多くのコードではないからです。

于 2012-08-21T19:54:27.543 に答える
2

作成するのではなく、作成または使用classesできます。個人的には、. これにより、アプリの柔軟性が高まり、手間をかけずにオブジェクトを操作できるようになると思います。それらを設定するには時間がかかることはわかっていますが、一度設定すると、使用して解析するのがかなり簡単になります。arrayshashmapclassesArrayListJSON

于 2012-08-21T12:41:44.607 に答える