json - Gson - 具有空值的 JsonObject
问题描述
我对 Gson 如何将字符串解析为 JSON 有点困惑。一开始,我像这样初始化 gson
val gson = Gson().newBuilder().serializeNulls().disableHtmlEscaping().create()
接下来,我将我的地图转换为字符串:
val pushJson = gson.toJson(data) // data is of type Map<String,Any>
这给出了以下输出:
{
"name": null,
"uuid": "5a8e8202-6654-44d9-a452-310773da78c1",
"paymentCurrency": "EU"
}
此时,JSON 字符串具有空值。但在以下步骤中:
val jsonObject = JsonParser.parseString(pushJson).asJsonObject
它没有!
{
"uuid": "5a8e8202-6654-44d9-a452-310773da78c1",
"paymentCurrency": "EU"
}
空值被省略。如何在 JSON 字符串中获取 JsonObject 中的所有空值:
{
"string-key": null,
"other-key": null
}
@编辑
添加了一些 json 来帮助理解问题。
解决方案
在与 OP 讨论后发现 JSON 对象随后由 Retrofit 序列化以允许 API 调用,使用以下代码:
return Retrofit.Builder()
.baseUrl("api/url")
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiInterface::class.java)
这里的问题在于GsonConverterFactory
:由于没有将Gson
对象传递给该create
方法,Gson
因此会在后台创建一个新的默认实例,并且默认情况下它不会序列化null
值。
通过将适当的实例传递给工厂可以轻松解决该问题:
val gson = GsonBuilder().serializeNulls().create() // plus any other custom configuration
....
fun createRetrofit() = Retrofit.Builder()
.baseUrl("api/url")
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson)) // use the configured Gson instance
.build()
.create(ApiInterface::class.java)
推荐阅读
- php - 从服务器移到另一个服务器后,$_REQUEST 不起作用
- c# - 如何在本地用户中运行应用程序
- excel - 如何在从 Excel 工作表导入消息时使用换行符向 Microsoft 团队发送消息
- python - Python Imports - 参考顶级模块而不是“内级”模块
- javascript - 如何从 Google 表格中的一系列单元格中获取值并将其与预定义的值进行比较以在条件满足时发送邮件
- database - 数据库:记录资源锁定状态的最佳实践?
- gcloud - 为什么在 gcloud 命令中需要区域/区域
- git - 在 git 中查找特定行的作者
- swift - 斯威夫特用户界面。如何更改 TextField 的占位符颜色?
- css - SVG dasharray 长度不会随着更大的屏幕尺寸而扩大