用Gson解析嵌套的Json对象

时间:2015-01-06 19:30:59

标签: java android json gson

我是Gson解析新手,做了一些例子,但这次我的json很复杂,看起来像这样

{
  "message": "Ok",
  "code": 200,
  "data": {
    "storage": {
      "39": {
        "weight": 22000,
        "verificationPackageRequested": null,
        "id": 39,
        "countryCode": "US",
        "photosPackageRequested": null,
        "created": "2014-12-30 11:27:57",
        "ItemPrice": 224.99,
        "ItemTitle": "Apple iPad Mini MF432LL/A (16GB, Wi-Fi, Space Gray )",
        "PhotoThumbnail": "/upload/storage-products/b8c2839010a8c5aae21df3b9e57125d0_photoThumbnail.jpg"
        "items": [
          {
        "weight": 22000,
        "verificationPackageRequested": null,
        "id": 39,
        "countryCode": "US",
        "photosPackageRequested": null,
        "created": "2014-12-30 11:27:57",
        "ItemPrice": 224.99,
        "ItemTitle": "Apple iPad Mini MF432LL/A (16GB, Wi-Fi, Space Gray )",
        "PhotoThumbnail": "/upload/storage-products/b8c2839010a8c5aae21df3b9e57125d0_photoThumbnail.jpg"
          }
        ],
        "cellStatus": null,
        "orderStorageIsMfPackage": 0,
        "storageImage": "/upload/storage/storage_6_thumbnail.jpg"
      }
    }
  },
  "error": false
}

我试过这种方式

static class Page{
    String message;
    int code;
    Data data;
    //getters+setters
}
static class Data{
    HashMap<Values,String> storage;
}
static class Values{
    String PhotoThumbnail;
    String ItemTitle;
    String  showPrice;
    String weight;
    String symbol;
    String created;
    String id;
    String photosPackageRequested;
    String verificationPackageRequested;
    String countryCode;
    //getters+setters
    @Override
    public String toString(){
        return PhotoThumbnail+ " - "+ItemTitle+" - "+showPrice+" - "+weight+" - "+symbol+" - "+created+" - "+id+" - "+photosPackageRequested+" - "+verificationPackageRequested+" -"+countryCode;
    }
}

}

并通过这样的结果

Gson gson = new GsonBuilder().create();
Page wp=gson.fromJson(json,Page.class) ;

但是我无法让它工作,它显示存储为空,我无法理解为什么,plsease帮助

1 个答案:

答案 0 :(得分:0)

这是因为你有39项:

data
   '-storage
      '-39
          '-items [item...]

如果您将“39”更改为“changeIT”,例如:

...
"data": {
    "storage": {
        "changeIT": {
            "orderStorageIsAlone": 1,
...

您可以使用型号:

static class Wrapper {

    Data data;
}

static class Data {

    Storages storage;
}

static class Storages {

    ChangeIT changeIT;
}

static class ChangeIT {

    List<RItems> items;

    public ChangeIT() {
        items = new ArrayList<>();
    }
}

static class RItems {

    String PhotoThumbnail;
    String ItemTitle;
    String showPrice;
    String weight;
    String symbol;
    String created;
    String id;
    String photosPackageRequested;
    String verificationPackageRequested;
    String countryCode;
    ...

(这是一个例子)

您不能将数字用作类名,因此我不知道如何映射瞬态元素。