android - Kotlin 中的 Gson toJson 和 ArrayList

标签 android kotlin gson retrofit retrofit2

类似于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/

相关文章:

android - 抽屉导航 Android API 特定的布局属性

android - DevicePolicyManager.resetPasswordWithToken 抛出 NPE

android - 改造发布空数据

java - 使用 apache commons io 时如何解决错误 403?

android - 使用 ROOM 和 @Database 注释执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

java - 如何判断类的类型并通过fromJson方法括号传递给gson

android - 如何在 Switch/SwitchCompat 按钮中设置宽度和轨道文本并实现此结果? (附上图片和GIF)

Android 深度链接无法捕获重定向 url

android - 我们可以在另一个类中使用来自其他类的可组合函数吗?

android - Android中的文字闪烁,用最简洁的Kotlin