Gson + Kotlin 组合中实现默认值和空安全的最优雅的的方式

本文介绍了如何在Gson和Kotlin组合中优雅地处理默认值和空安全问题,避免使用大的反射库,并提供了解决方案。尽管存在Moshi等库,但在已使用Gson或Jackson的项目中,文章提出了通过@SerializedName注解和定制构造函数来实现所需功能,同时避免了大量冗余代码。最后,文章提到了2018年5月Moshi增加了对Kotlin的完全支持,成为了一个更好的选择。
摘要由CSDN通过智能技术生成

原文地址

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值