1

Similarly to this question, I would like to convert an object (actually, it is a API response from retrofit) to a json string, so it would be simpler to store it somewhere.

The response structure is something like these:

{
  "metadata": {
    "count": 0,
    "type": "string"
  },
  "results": [
    {
      "obj1": {
        "param1": "s1",
        "param2": "s2"
      },
      "obj2": {
        "param3": 0,
        "param4": 0,
        "param5": 0
      },
      "obj3": 0,
      "obj4": "27/12/2017"
    }
  ]
}

Using retrofit2, I have the results array stored in a List<MyResponse.Result> and that's the parameter I'm passing to Gson().toJson, like so:

var contentResponse: String = ""
try{
    this.contentResponse.plus(Gson().toJson(response))
} catch (e: Exception){
    Log.e("Gson error", e.toString())
}

Unfortunately, I'm getting no exception but my contentResponse keeps empty. I`ve tried to use the method in the question mentioned above, but got the same outcome. Any advises?

PS: If there is an easier way to get the retrofit response in a String, it could help as well.

lucas.mdo
  • 339
  • 7
  • 27

1 Answers1

3

Strings are immutable in JVM. Calling

this.contentResponse.plus(Gson().toJson(response))

is equivalent to

this.contentResponse + (Gson().toJson(response))

This way you can see better that you are not assiging the result to anything. Change it to

this.contentResponse = this.contentResponse.plus(Gson().toJson(response))
Alberto S.
  • 7,409
  • 6
  • 27
  • 46