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
import kotlinx.android.parcel.Parcelize
//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.
@Parcelize
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

california-query-json.PNG

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.example.android.politicalpreparedness.network.models.Division
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson

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

    @ToJson
//Parsing class object into json string
    fun divisionToJson (division: Division): String {
        return division.id
    }
}

Check out ElectionAdapter.kt on github

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

val moshi = Moshi.Builder()
    .add(ElectionAdapter())
    .build()

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

 
Share this