Kotlin Gson toJson returns double quoted string

Viewed 186

I am trying to encode JSON object from Kotlin object:

class RequestData(val phone: String)

...

val requestJson = Gson().toJson(RequestData("79008007060"))

After encoding I am getting quoted string

"{\"phoneNumber\":\"\"}"

instead

{"phoneNumber":""}

Could you tell me why does it happen and how to fix it?

1 Answers

I found a solution. I made mistake in other place. I tried to send POST JSON request to server with Retrofit and encoded object to JSON-string before put it to @Body:

interface AuthService {
    @POST("requestPinCode")
    fun requestPinCode(@Body body: String): Observable<ApiResult>
}

...

data class RequestData(val phone: String)

...

val requestJson = Gson().toJson(RequestData("79008007060"))
authService.requestPinCode(requestJson)

But right way is to put not encoded object to @Body

interface AuthService {

    @POST("requestPinCode")
    fun requestPinCode(@Body body: RequestData): Observable<ApiResult>

}

...

data class RequestData(val phone: String)

...

authService.requestPinCode(RequestData("79008007060"))
Related