Using Retrofit to access JSON arrays

前端 未结 5 1446
情话喂你
情话喂你 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:27

    You should be able to directly access the com.google.gson.JsonObject from Retrofit, and access whatever field you would like. So if you are only interested in the Photo array something like this should works:

    interface ArtService {
        @GET("/services/rest/?method=flickr.photos.getRecent&extras=url_l&owner_name&format=json")
        JsonObject getPhotos();
    
        public class Photo {
             int id;
             String title;
             String owner;
             String url_l;
        }
    }
    

    And when you actually call the service just run the JsonObject to get what you want:

        JsonObject json = mRestClient.getArtService().getPhotos();
        List photos = new Gson().fromJson(json.getAsJsonObject("photos").get("photo").toString(), new TypeToken>() {}.getType());
    

    Of course all the sanity check are left to you.

提交回复
热议问题