Using Retrofit to access JSON arrays

前端 未结 5 1449
情话喂你
情话喂你 2020-12-07 19:18

I thought I understood how to do this, but obviously not. I have my API from Flickr, which begins like so:

jsonFlickrApi({
   \"photos\":{
      \"page\":1,         


        
5条回答
  •  悲&欢浪女
    2020-12-07 19:38

    A quick look at Retrofit's docs says it uses Gson to convert JSON to Java classes. This means you need a class hierarchy in Java that matches the JSON. Yours ... doesn't.

    The returned JSON is an object with a single field "photos" that holds an object;

    { "photos" : { ... } }
    

    So, your top level class would be a Java class with a single field:

    public class PhotosResponse {
        private Photos photos;
    
        // getter/setter
    }
    

    And that Photos type would be another class that matches the JSON for the object that field contains:

    { "page":1, "pages":10, ... }
    

    So you'd have:

    public class Photos {
        private int page;
        private int pages;
        private int perpage'
        private int total;
        private List photo;
    
        // getters / setters
    }
    

    And then you'd create a Photo class to match the structure of the object in that inner array. Gson will then map the returned JSON appropriately.

提交回复
热议问题