- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我正在尝试使用 PolymorphicJsonAdapterFactory为了获得不同的类型,但总是遇到奇怪的异常: Missing label for test_type 我的实体: @JsonCl
我有一个 moshi PolymorphicJsonAdapterFactory,它工作得很好。 .withSubtype(ColdWeather::class.java, "Cold") .with
我有一个包含两种具体类型的接口(interface),作为我的模型的一部分,我想使用 Moshi 对其进行序列化/反序列化。我的问题是,我不完全理解 PolymorphicJsonAdapterFac
我是一名优秀的程序员,十分优秀!