In Kotlin you can create a data class:

data class CountriesResponse(
    val count: Int,
    val countries: List<Country>,
    val error: String)

然后可以使用它来解析JSON,例如,"{n:10}".在本例中,您将有一个从RetrofitFuelGson接收的对象val countries: CountriesResponse,其中包含以下值:count = 0, countries = null, error = null.

In Kotlin + Gson - How to get an emptyList when null for data class you can see another example.

当您稍后try 使用countries时,您将在这里得到一个异常:val size = countries.countries.size:"kotlin.TypeCastException:null不能转换为非null类型kotlin.Int".如果您编写代码并在访问这些字段时使用?,Android Studio将突出显示?.并警告:Unnecessary safe call on a non-null receiver of type List<Country>.

So, should we use ? in data classes? Why can an application set null to non-nullable variables during runtime?

推荐答案

This happens because Gson uses an unsafe (as in java.misc.Unsafe) instance construction mechanism to create instances of classes, bypassing their constructors, and then sets their fields directly.

看到这个问题了吗;A对于一些研究:Gson Deserialization with Kotlin, Initializer block not called.

因此,Gson忽略了构造逻辑和类状态不变量,因此不建议将其用于可能受此影响的复杂类.它也会忽略setters中的值判断.

Consider a Kotlin-aware serialization solution, such as Jackson (mentioned in the Q&A linked above) or kotlinx.serialization.

Kotlin相关问答推荐

只能在元素区域中点击的Jetpack Compose列

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

Kotlin-elvis算子don';不使用map.get()

如何在 Kotlin 中初始化 Short 数组?

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

顶级属性的初始化

Jetpack compose 可滚动表格

如何通过 compose 处理剪切区域?

在 Kotlin 中,::class.simpleName是做什么的?

将 Firebase 数据快照反序列化为 Kotlin 数据类

以编程方式重新启动 Spring Boot 应用程序/刷新 Spring 上下文

Kotlin中的测试无法访问受保护(protected)的方法

从命令行运行Java到Kotlin转换器?

Kotlin - 具有私有构造函数的类的工厂函数

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

Android Jetpack Compose 中的文本渐变

如何在 firebase 数据库中使用 kotlin 协程

如何在 Fragment 中使用 Anko DSL?