Moshi自定义适配器将json镜像类转换为另一个

时间:2020-05-13 19:11:47

标签: json kotlin moshi

在Moshi文档中,它声明了创建镜像JSON形状的类的能力,然后创建一个自定义适配器以告诉它如何将该类转换为所需形状的另一个类。我正在尝试这样做,但这就像自定义适配器没有被执行一样。

我的自定义适配器如下:

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;
    }
}

我在这里将适配器添加到Moshi

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)

如果我正确理解了文档,应该将json转换为LocationJson对象,然后使用自定义适配器将LocationJson对象转换为Location对象。我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:2)

将自定义适配器添加到Moshi构建器时,KotlinJsonAdapterFactory()总是必须排在最后。最后添加它可以解决问题

val moshi = Moshi.Builder().add(LocationJsonAdapter()).add(KotlinJsonAdapterFactory()).build()