gpt4 book ai didi

Moshi:PolymorphicJsonAdapterFactory 是否可以获取 withDefaultValue 中的类型?

转载 作者:行者123 更新时间:2023-12-05 04:47:04 25 4
gpt4 key购买 nike

我有一个 moshi PolymorphicJsonAdapterFactory,它工作得很好。

.withSubtype(ColdWeather::class.java, "Cold")
.withSubtype(HotWeather::class.java, "Hot")
.withDefaultValue(//how to grab the label)

withDefaultValue 方法是一个很好的包罗万象的方法,但我的 BE 团队希望我记录下来的实际标签,以帮助捕获他们端发生的错误。据我所知...在 withDefaultValue 中我无法获取对标签的引用,在这种情况下后端发回“中”。

我觉得必须有一种方法来获取这个标签(但我遗漏了一些简单的东西?)所以我可以记录它并可能在 withDefaultValue 方法中传播它。

最佳答案

我刚才偶然发现了这个问题。我发现仅使用 .withDefaultValue 方法是不可能实现的。到目前为止,除了 .withFallbackJsonAdapter(我使用的是 moshi 1.12 版),我没有找到更好的解决方案,它可以让你手动解析 json,以防你的 PolymorphicJsonAdapterFactory 不知道标签> 适配器。文档说:

/**
* Returns a new factory that with default to {@code fallbackJsonAdapter.fromJson(reader)} upon
* decoding of unrecognized labels.
*
* <p>The {@link JsonReader} instance will not be automatically consumed, so make sure to consume
* it within your implementation of {@link JsonAdapter#fromJson(JsonReader)}
*/
public PolymorphicJsonAdapterFactory<T> withFallbackJsonAdapter(
@Nullable JsonAdapter<Object> fallbackJsonAdapter) {
return ...
}

我假设你的代码有点像这样(简化):

    interface Weather {
val type: String
}

@JsonClass(generateAdapter = true)
class ColdWeather( @Json(name = "type") override val type: String) : Weather

@JsonClass(generateAdapter = true)
class HotWeather( @Json(name = "type") override val type: String) : Weather

val weatherAdapter = PolymorphicJsonAdapterFactory.of(Weather::class.java, "type")
.withSubtype(ColdWeather::class.java, "Cold")
.withSubtype(HotWeather::class.java, "Hot")

你会收到一个类似这样的 json:

{“天气” : {“类型”:“冷”}

要接收未知标签,我会这样做:

class UnknownWeather(override val type: String) : Weather

val weatherAdapter = PolymorphicJsonAdapterFactory.of(Weather::class.java, "type")
.withSubtype(ColdWeather::class.java, "Cold")
.withSubtype(HotWeather::class.java, "Hot")
.withFallbackJsonAdapter((object : JsonAdapter<Any>() {
override fun fromJson(reader: JsonReader): UnknownWeather {
var type = ... // parse it from the reader
return UnknownWeather(type)
}

override fun toJson(writer: JsonWriter, value: Any?) {
// nothing to do
}
}))

当然,这意味着您必须深入了解 JsonReader,但它有一个相当容易理解的界面,您基本上可以遍历 json 对象的属性并提取您需要的内容,在我们的案例只是“类型”属性。

仅供引用,似乎更多人对此有疑问:https://github.com/square/moshi/issues/784

关于Moshi:PolymorphicJsonAdapterFactory 是否可以获取 withDefaultValue 中的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68629197/

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