gpt4 book ai didi

kotlin - 为什么Moshi在用fromJson解析json时返回一个可为空的对象?

转载 作者:行者123 更新时间:2023-12-02 12:48:19 25 4
gpt4 key购买 nike

可能只是我用错了,因为我是 Kotlin 和 Moshi 的新手。
data class InitialAppResult(val status: Int, val message: String, val baseprm: String)

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()  
val adapter = moshi.adapter(InitialAppResult::class.java)
val fromJson = adapter.fromJson(result.get())

为什么 fromJson 可以为空并且需要一个 !!或者 ?。例如: fromJson!!.baseprm
如果解析失败并且缺少必填字段,它只会在我的情况下引发异常。那么它如何解析“无效”的 JSON 响应而不失败,即返回 null?

最佳答案

Moshi 是一个用 Java 实现的库,而您的代码是用 Kotlin 编写的。引用文档中的“Calling Java code from Kotlin”部分:

Any reference in Java may be null, which makes Kotlin's requirements of strict null-safety impractical for objects coming from Java.


这意味着任何来自 Java 的对象在默认情况下都是可为空的。
但是,如果您将变量声明为不可为空类型,Kotlin 将自动“强制转换”它:

When a platform value [i.e., a Java object in this case] is assigned to a Kotlin variable, we can rely on type inference (the variable will have an inferred platform type then, as item has in the example above), or we can choose the type that we expect (both nullable and non-null types are allowed).


这是一个示例(同样来自上面链接的文档),其中 item是一个 Java 对象:
val nullable: String? = item // allowed, always works
val notNull: String = item // allowed, may fail at runtime
因此,在您的情况下,您可以通过键入以下内容强制对象不可为空:
val fromJson: InitialAppResult = adapter.fromJson(result.get())
编辑
在这种情况下,所有 fromJson方法定义为 @Nullable (因为 null 是一个有效的 JSON 值),这意味着结果可以是 null ,所以推断的类型可以为空。这同样适用于 @NotNull .所以这些注解在 Java 和 Kotlin 互操作的情况下非常有用。
在其他情况下, @Nullable@NotNull缺少注释,上面关于将值显式添加到变量的说法是正确的。
编辑 21/07/2020

Why does fromJson is marked as @Nullable?


原因是 null是有效的 JSON 值。以下示例都是有效的 JSON 字符串:
  • null
  • { "key": null }

  • 因此, JsonAdapter需要能够处理 null值。例如,以下是内置 ObjectJsonAdapter 的方法处理 null s:
    @Override public Object fromJson(JsonReader reader) throws IOException {
    ...
    case NULL:
    return reader.nextNull();
    }
    这依赖于 nextNull , 其 documentation说:

    Consumes the next token from the JSON stream and asserts that it is a literal null. Returns null.

    关于kotlin - 为什么Moshi在用fromJson解析json时返回一个可为空的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090532/

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