Moshi 自定义适配器转换 json 镜像 class 到另一个

Moshi custom adapter convert json mirror class to another

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

我的自定义适配器如下所示:

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 对象。我在这里做错了什么吗?

将自定义适配器添加到 Moshi 构建器时,KotlinJsonAdapterFactory() 始终必须放在最后。最后添加它解决了问题

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