【问题标题】:Gson - JsonObject with null valuesGson - 具有空值的 JsonObject
【发布时间】:2019-11-29 13:56:31
【问题描述】:

我对 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 来帮助理解问题。

【问题讨论】:

  • 能否请您粘贴一些可以重现该问题的代码?我不太明白问题是什么
  • 当然,我已经编辑了问题
  • 你试过这个吗:Gson gson = new GsonBuilder().serializeNulls().create();
  • 是的,你可以看到这是我问题的第一行 :)
  • @shurrok 你用的是什么版本的 GSON?

标签: json kotlin gson


【解决方案1】:

在与 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 实例,默认情况下它不会序列化@ 987654326@ 值。

通过将适当的实例传递给工厂可以轻松解决该问题:

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)

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多