There are already multiple articles and sources about using Kotlin and JSON. First of, there is the Awesome-Kotlin list about JSON libraries. Then, there are multiple articles like this one, talking about how to handle Kotlin data classes with json. The author uses Moshi, which has easy to use Kotlin support. What the challenge of using Kotlin and JSON boils down to is: We want to use Kotlin data classes for concise code, non-nullable types for null-safety and default arguments for the data class constructor to work when a field is missing in a given JSON. We also would probably want explicit exceptions when the mapping fails completely (required field missing). We also want near zero overhead automatic mapping from JSON to objects and in reverse. On android, we also want a small APK size, so a reduced number of dependencies and small libraries. Therefore:
关于Kotlin中对JSON的处理,网上已经有太多的文章和资源了。首先,在Awesome-Kotlin(在github混过的估计都知道这个约定吧)列表里有一些列JSON处理库。然后,还有许多像这篇文章一样,讨论关于如何处理Kotlin data classes 和 JSON。这篇文章的作者使用了Moshi,一个对Kotlin支持非常好的库。使用Kotlin和JSON的最大挑战是:
- 我们希望用简洁的代码使用Kotlin数据类
- 以null安全的方式使用非空类型
- 通过数据类构造函数创建数据类时,在给定JSON中缺少字段时使用默认值
- 当映射失败时,我们还可能需要显式异常处理(例如需要知道哪个字段映射失败了)
- 我们还希望从JSON到对象的自动映射的开销接近于0,反之也一样
- 在Android平台下,我们还希望APK包尽量小,所以我们希望能做到更少的依赖和更小的库
因此:我们不想使用android的org.json,因为它的功能非常有限,根本没有映射功能。
据我所知,为了使用Kotlin已知的一些特性,例如空安全和默认参数等,所有的第三方库都是用了kotlin的反射库。kotlin的反射库差不多有2MB,这对于移动平台来说太大了,所以不建议用。
We might not have the ability to use a library like Moshi with integrated Kotlin support, because we already use the popular Gson or Jackson library used in the project.
我们可能无法使用像Moshi这样具有集成Kotlin支持的库,因为我们已经使用了项目中使用的流行的Gson或Jackson库。
This post describes a way of using the normal Gson library (Kotson only adds syntactic sugar, so no added functionality) with