Gson - 具有空值的 JsonObject

Gson - JsonObject with null values

我对 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"
}

省略空值。如何获取 JsonObject 中的所有空值,如 JSON string:

{
  "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)