【问题标题】:GSON - convert a string into a JsonArrayGSON - 将字符串转换为 JsonArray
【发布时间】:2023-03-21 09:49:01
【问题描述】:

我正在尝试将字符串转换为 JsonArray。到目前为止,我已尝试执行以下操作:

Gson().toJson(string)

Gson().toJsonTree(string)

两者都抛出异常,说明参数不是 JsonArray。

这是字符串,你可以看到它是一个 JsonArray:

"[{\"match\":{\"id\":92757102,\"tournament_id\":3666234,\"state\":\"open\",\"player1_id\":58602461,\"player2_id\":58602459,\"player1_prereq_match_id\":null,\"player2_prereq_match_id\":null,\"player1_is_prereq_match_loser\":false,\"player2_is_prereq_match_loser\":false,\"winner_id\":null,\"loser_id\":null,\"started_at\":\"2017-07-17T19:10:07.588-04:00\",\"created_at\":\"2017-07-17T19:10:07.476-04:00\",\"updated_at\":\"2017-07-17T19:10:07.588-04:00\",\"identifier\":\"A\",\"has_attachment\":false,\"round\":1,\"player1_votes\":null,\"player2_votes\":null,\"group_id\":null,\"attachment_count\":null,\"scheduled_time\":null,\"location\":null,\"underway_at\":null,\"optional\":false,\"rushb_id\":null,\"completed_at\":null,\"suggested_play_order\":1,\"prerequisite_match_ids_csv\":\"\",\"scores_csv\":\"\"}}]"

【问题讨论】:

  • new Gson().fromJson(string) ?
  • 这不是 JSON 数组。那是一个 JSON 字符串。您重新编码了 JSON 数组。

标签: java json gson kotlin


【解决方案1】:

Gson().fromJson(string, JsonArray::class.java)

【讨论】:

  • 请查看how to answer 并更新您的答案以提供更多详细信息。具体来说,如果您解释一下这是如何解决问题的,将会很有帮助
【解决方案2】:

toJson() 将 json 对象呈现为(json 的)字符串。

您需要 fromJson() 方法,它将字符串转换为 json 对象。

试试:

new Gson().fromJson(string, JsonArray.class)

【讨论】:

  • 这不会引发异常。他们一定是打错了。
  • @SotiriosDelimanolis 也不例外。 OP 将“抛出异常”与“编译器错误”混淆了。
  • 也许吧。您建议的代码仍然存在编译错误。
  • @SotiriosDelimanolis 对。我在那里太快了。现在怎么样。
  • 是的,可以编译但无法解析他们问题中的字符串。
猜你喜欢
  • 1970-01-01
  • 2015-02-16
  • 2013-03-30
  • 2011-09-21
  • 2012-04-28
  • 2017-03-14
  • 2013-05-08
  • 1970-01-01
  • 2017-06-04
相关资源
最近更新 更多