Gson toJson和ArrayList在Kotlin
类似于这个问题,我想将一个对象(实际上,它是一个来自翻新的API响应)转换成json字符串,所以将它存储在某个地方会更简单。
响应结构是这样的:
{ "metadata": { "count": 0, "type": "string" }, "results": [ { "obj1": { "param1": "s1", "param2": "s2" }, "obj2": { "param3": 0, "param4": 0, "param5": 0 }, "obj3": 0, "obj4": "27/12/2017" } ] }
使用List
,我将结果数组存储在一个List
,这是我传递给Gson().toJson
,如下所示:
var contentResponse: String = "" try{ this.contentResponse.plus(Gson().toJson(response)) } catch (e: Exception){ Log.e("Gson error", e.toString()) }
不幸的是,我没有例外,但我的contentResponse
保持空白。 我试图在上面提到的问题中使用这个方法,但得到了相同的结果。 任何建议?
PS:如果有更简单的方法来获得字符串的改造响应,也可以帮助。
字符串在JVM中是不可变的。 调用
this.contentResponse.plus(Gson().toJson(response))
相当于
this.contentResponse + (Gson().toJson(response))
这样,你可以更好地看到,你没有把结果分配给任何东西。 将其更改为
this.contentResponse = this.contentResponse.plus(Gson().toJson(response))