Search code examples
androidkotlingsonretrofituri

How to parse a String to Android.Uri with Retrofit and Gson


I'm making an Android app and I'm using retrofit with Gson. One of the types I'm requesting is called Photo from the api has two Urls in it, both are links to pictures.

data class Photo(val id: Int, val title: String, val pictureUrl: Uri, val thumbnailUrl: Uri)

I'd prefer if retrofit would parse the Json directly to the class and I was thinking of writing an extra Gson Adapter. But I haven't been able to find a comprehensible example in Kotlin. Also thought about using an extra converterfactory??? But that doesn't seem right.

What would be the way to go on this problem?


Solution

  • You can use this code example:

    class UriDeserializer : JsonDeserializer<Uri> {
    
        override fun deserialize(
            json: JsonElement?,
            typeOfT: Type?,
            context: JsonDeserializationContext?
        ): Uri {
            return Uri.parse(json?.asString)
        }
    }
    

    And register this deserializer when creating the Gson instance:

    GsonBuilder().registerTypeAdapter(Uri::class.java, UriDeserializer())
            .create()