首页 > 解决方案 > 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 来帮助理解问题。

标签: jsonkotlingson

解决方案


在与 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)

推荐阅读