Reputation: 2777
In the Moshi documentation it states the ability to create a class that mirrors the shape of the JSON and then a custom adapter to tell it how to convert that class to another in the desired shape. I'm trying to do that, but it's as if the custom adapter isn't being executed.
My custom adapter looks like this:
class LocationJsonAdapter {
@FromJson
fun fromJson(locationJson: LocationJson): Location {
val location = Location()
location.city.name = locationJson.city.name.en
location.country.name = locationJson.country.name.en
location.continent.name = locationJson.continent.name.en
location.subdivisions.forEachIndexed {index, subdivision ->
subdivision.name = locationJson.subdivisions[index].name.en
}
return location;
}
}
I'm adding the adapter to Moshi here
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).add(LocationJsonAdapter()).build()
val jsonAdapter: JsonAdapter<Location> = moshi.adapter(Location::class.java)
val location: Location? = jsonAdapter.fromJson(data)
println(location)
If I understand the documentation correctly, it's supposed to convert the json to a LocationJson
object and use the custom adapter to then convert the LocationJson
object into a Location
object. Am I doing something wrong here?
Upvotes: 1
Views: 903
Reputation: 2777
When adding the custom adapter to the Moshi builder, the KotlinJsonAdapterFactory()
always has to go last. Adding it last fixed the issue
val moshi = Moshi.Builder().add(LocationJsonAdapter()).add(KotlinJsonAdapterFactory()).build()
Upvotes: 3