【问题标题】:Moshi custom adapter convert json mirror class to anotherMoshi 自定义适配器将 json 镜像类转换为另一个
【发布时间】:2020-05-14 10:15:29
【问题描述】:

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

【问题讨论】:

    标签: json kotlin moshi


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2017-02-08
      • 2018-06-17
      • 2016-01-26
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2021-04-01
      相关资源
      最近更新 更多