gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:17:49 24 4
gpt4 key购买 nike

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

最佳答案

将自定义适配器添加到Moshi构建器时,KotlinJsonAdapterFactory()总是必须排在最后。最后添加它解决了这个问题
val moshi = Moshi.Builder().add(LocationJsonAdapter()).add(KotlinJsonAdapterFactory()).build()

关于json - Moshi自定义适配器将json镜像类转换为另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61782990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com