Challenge: Adding a Custom Gson Deserializer

PhotoDeserializer.kt

import com.bignerdranch.android.photogallery.GalleryItem
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import java.lang.reflect.Type

class PhotoDeserializer: JsonDeserializer<PhotoResponse> {
    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): PhotoResponse {
        val jsonObject:JsonObject = json?.asJsonObject!!
        val jsonArray = jsonObject.get("photo").asJsonArray
        val photoResponse:PhotoResponse = PhotoResponse()
        val photos:MutableList<GalleryItem> = mutableListOf()
        jsonArray.forEach {photo ->
            val photoElement = photo.asJsonObject
            val galleryItem:GalleryItem = GalleryItem(
                photoElement.get("title").asString,
                photoElement.get("id").asString,
                photoElement.get("url_s").asString
            )
            photos.add(galleryItem)
        }
        photoResponse.galleryItems = photos
        return photoResponse
    }

}

FlickrFetchr.kt>

    val gson:Gson = GsonBuilder().registerTypeAdapter(PhotoResponse::class.java, PhotoDeserializer()).create()
    val retrofit = Retrofit.Builder()
        .baseUrl("https://api.flickr.com/")
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
1 Like

I tried your solution but at the end i get empty list. after debugging i notice that jsonObject.get(“photo”) return a null. Maybe due to casting jsonArray to jsonObject. However, calling jsonObject.getAsJsonArray(“photo”) fix the problem.

val jsonArray = jsonObject.getAsJsonArray(“photo”)

EDIT 2:
another issue which is getting “photo” memeber before “photos” and other thing is using !! which can lead to serious problem like NullPointerException

val jsonObject = json?.asJsonObject?.get(“photos”)?.asJsonObject
val jsonArray = photoJsonObject?.getAsJsonArray(“photo”)?.asJsonArray