【问题标题】:Kotlin Gson toJson returns double quoted stringKotlin Gson toJson 返回双引号字符串
【发布时间】:2021-11-29 08:10:02
【问题描述】:

我正在尝试从 Kotlin 对象编码 JSON 对象:

class RequestData(val phone: String)

...

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

编码后我得到引用的字符串

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

改为

{"phoneNumber":""}

您能告诉我为什么会发生这种情况以及如何解决吗?

【问题讨论】:

  • 无法重现。您是否可能第二次在requestJson 上执行toJson?或者您是在某种调试器中检查requestJson 的内容,而不是打印出来?
  • 你是如何观察值的?
  • 我的错。我尝试发送 POST JSON 请求并根据需要将 json-string 放入 @Body 而不是对象... :( 抱歉问题不正确!准备好不喜欢...
  • @pirogtm 这不是一个无效的问题。您可以用您如何观察该值以及它为什么给您这个结果来回答自己。将来它可能会帮助其他人。

标签: kotlin gson


【解决方案1】:

我找到了解决方案。我在其他地方犯了错误。我尝试使用 Retrofit 将 POST JSON 请求发送到服务器,并将编码对象发送到 JSON 字符串,然后再将其发送到 @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)

但正确的方法是将未编码的对象放入@Body

interface AuthService {

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

}

...

data class RequestData(val phone: String)

...

authService.requestPinCode(RequestData("79008007060"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多