2017-07-17 644 views
-2

我想将字符串转换为JsonArray。到目前为止,我已经尝试做如下:GSON - 将字符串转换为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\":\"\"}}]" 
+1

'新GSON()fromJson(串)'? – Bohemian

+0

这不是一个JSON数组。这是一个JSON字符串。您重新编码了JSON数组。 –

回答

-1

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

+0

请看[如何回答](https://stackoverflow.com/help/how-to-answer)并更新您的答案以提供更多详细信息。具体来说,如果你解释了如何解决这个问题,这将是有帮助的 – Ortund

-1

toJson()呈现一个JSON对象(的JSON)的字符串。

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

尝试:

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

这不会引发异常。他们必须错误输入。 –

+0

@SotiriosDelimanolis没有例外。 OP将“抛出异常”与“编译器错误”混为一谈。 – Bohemian

+0

也许吧。尽管你的代码仍然有编译错误。 –