类似于this问题,我想将一个对象(实际上是retrofit 的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"
}
]
}
使用 retrofit2,我将结果数组存储在 List<MyResponse.Result>
中这就是我传递给 Gson().toJson
的参数,像这样:
var contentResponse: String = ""
try{
this.contentResponse.plus(Gson().toJson(response))
} catch (e: Exception){
Log.e("Gson error", e.toString())
}
不幸的是,除了我的 contentResponse
之外,我没有任何异常(exception)。保持空。我尝试使用上述问题中的方法,但得到了相同的结果。有什么建议吗?
PS:如果有更简单的方法来获取字符串中的改造响应,它也会有所帮助。
最佳答案
字符串在 JVM 中是不可变的。呼唤
this.contentResponse.plus(Gson().toJson(response))
相当于
this.contentResponse + (Gson().toJson(response))
这样您可以更清楚地看到您没有将结果分配给任何东西。改成
this.contentResponse = this.contentResponse.plus(Gson().toJson(response))
关于android - Kotlin 中的 Gson toJson 和 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988572/