Clevers Rungene


Clevers Rungene

Custom Type Adapters(ElectionAdapter)

Custom Type Adapters(ElectionAdapter)

Part 5

Clevers Rungene's photo
Clevers Rungene
·Feb 7, 2022·

2 min read

Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.Read more

In our custom ElectionAdapter we convert data from Json to Kotlin Object and vice versa.

We have a data class Division.kt,

import android.os.Parcelable
//using Parcelable over Serializable. Parcelable is fully customizable, allowing developers to
// convert required data into Parcelable. Serialization is a marker interface as it converts an
// object into a stream using the Java reflection API. Due to this it ends up creating a number of
// garbage objects during the stream conversation process.
data class Division(
        val id: String,
        val country: String,
        val state: String
) : Parcelable

Check out Division.kt on github

The Division resource type in Civic Information API has method search. The search method, searches for political divisions by their natural name or OCD ID.

The API returns data in Json format


Raw HTTP Response

california-query-json-raw HTTP Response.PNG

ElectionAdapter.kt type adapter,

With Moshi, it’s particularly easy to customize how values are converted to and from JSON. A type adapter is any class that has methods annotated @ ToJson and @ FromJson

import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson

class ElectionAdapter {
//Parsing json string into class object
    fun divisionFromJson (ocdDivisionId: String): Division {
        val countryDelimiter = "country:"
        val stateDelimiter = "state:"
        val country = ocdDivisionId.substringAfter(countryDelimiter,"")
        val state = ocdDivisionId.substringAfter(stateDelimiter,"")
        return Division(ocdDivisionId, country, state)

//Parsing class object into json string
    fun divisionToJson (division: Division): String {

Check out ElectionAdapter.kt on github

Register the type adapter with the Moshi.Builder and we’re good to go.

val moshi = Moshi.Builder()

Thank you so much for reading, see you in part 6.

Share this