Challenge: Adding a Custom Gson Deserializer

The JSON response from Flickr contains multiple layers of nested data (Figure 24.6). In the section called Deserializing JSON text into model objects, you created model objects to map directly to the JSON hierarchy. But what if you did not care about the data in the outer layers? Wouldn’t it be nice to avoid cluttering your codebase with unnecessary model objects?

By default, Gson maps all of the JSON data directly to your model objects by matching Kotlin property names (or @SerializedName annotations) to JSON field names. You can customize this behavior by defining a custom com.google.gson.JsonDeserializer.

For this challenge, implement a custom deserializer to strip out the outermost layer of JSON data (the layer that maps to FlickrResponse). The deserializer should return a PhotoResponse object populated based on the JSON data. To do this, create a new class that extends from com.google.gson.JsonDeserializer and override the deserialize(…) function:

    class PhotoDeserializer : JsonDeserializer<PhotoResponse> {

        override fun deserialize(
            json: JsonElement,
            typeOfT: Type?,
            context: JsonDeserializationContext?
        ): PhotoResponse {
            // Pull photos object out of JsonElement
            // and convert to PhotoResponse object
        }
    }

Check out the Gson API documentation to learn how to parse through the JsonElement and convert it to a model object. (Hint: Look closely at the docs for JsonElement, JsonObject, and Gson.)

Once you create the deserializer, update the FlickrFetchr initialization code:

  • Use GsonBuilder to create a Gson instance and register your custom deserializer as a type adapter.

  • Create a retrofit2.converter.gson.GsonConverterFactory instance that uses the Gson instance as its converter.

  • Update the Retrofit instance configuration to use this custom Gson converter factory instance.

Finally, remove FlickrResponse from your project and update any dependent code accordingly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.82.58.213