Using Retrofit to access JSON arrays

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

    The accepted answer is correct but it requires building a PhotoResponse class which only has one object in it. This the following solution, we only need to create the Photos class and some sterilization.

    We create a JsonDeserializer:

    class PhotosDeserializer implements JsonDeserializer
    {
        @Override
        public Photos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    
            JsonElement content = json.getAsJsonObject().get("photos");
    
            return new Gson().fromJson(content, Photos.class);
    
        }
    
    }
    

    Now we create our custom gson object to Retrofit's RestAdapter:

        Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Photos.class, new PhotosDeserializer())
                        .create();
    

    And then we set the converter in the retrofit adapter:

     RestAdapter restAdapter = new RestAdapter.Builder()
                                                .setEndpoint(ArtService.ENDPOINT)
                                                .setConverter(new GsonConverter(gson))
                                                .build();
    

    And the interface would look like this:

    @GET("/?method="+METHOD_GET_RECENT+"&api_key="+API_KEY+"&format=json&nojsoncallback=1&extras="+EXTRAS_URL)
    public void getPhotos(Callback response);
    

    This way we get the Photos object without having to create PhotosResponse class. We can use it like this:

    ArtService artService = restAdapter.create(ArtService.class);
    artService.getPhotos(new Callback() {
        @Override
        public void success(Photos photos, Response response) {
    
            // Array of photos accessing by photos.photo
    
       }
    
       @Override
       public void failure(RetrofitError error) {
    
    
        }
    });
    

提交回复
热议问题