简体   繁体   中英

How to parse nested objects in json using Retrofit?

This is reddit/r/pic/.json data. I want to parse preview object and extract image URL.

{
"preview": {
"images": [
  {
    "source": {
      "url": "https://i.redditmedia.com/TIqBgNYhZaHMdHN61yUbFPDgDnsFCNkPi6Tb5p2Q-ac.png?s=9ee1ffdf902191de6be14972b7637866",
      "width": 772,
      "height": 762
    },
    "resolutions": [
      {
        "url": "https://i.redditmedia.com/TIqBgNYhZaHMdHN61yUbFPDgDnsFCNkPi6Tb5p2Q-ac.png?fit=crop&crop=faces%2Centropy&arh=2&w=108&s=2d74b9538ff6495f651ce8575baf46b5",
        "width": 108,
        "height": 106
      }
    ]
  }
 ]
}
}

You can have POJOs for those fields.

Example:

preview here is an object however images is an array/list.

You create a source class like this

class Source {
    private String url;
    private int width;
    private int height;
}

you can also see that resolutions array uses same keys/fields as the source class, this becomes more convenient to address

class Images {
    private Source source;
    private List<Soutrce> resolutions;
}

assuming you have a reddit class for parsing response, your preview will be

class Preview {
    private List<Images> images;
    // .. and some more fields if any
}

class Reddit {
    // ...above fields eg: over_18 and approved_by from your example
    private Preview preview;    
}

so your image will be at preview.images.get(0 /*position here*/).url;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM