【问题标题】:Retrofit/Spring Parsing Data Class to JSON ObjectRetrofit/Spring 将数据类解析为 JSON 对象
【发布时间】:2019-08-08 17:59:12
【问题描述】:

我有以下数据类:

data class Thing(
    val id: Long?,
    val title: String,
    val description: String,
)

在我的 API 中:

@POST("doThings")
    fun createThings(
        @Query("thing") thing: Thing
    ): Call<StatusResponse>

我得到了错误: status":500,"error":"Internal Server Error","message":"意外字符('E'(代码 69))

在spring api中我做了一个日志输出,数据类对象到达为:

“事物(id=null,title=Something,description=Something more)”

Retrofit Builder 有 GSON 转换器,但我猜它不能正常工作:

Retrofit.Builder()
            .client(get())
            .baseUrl(get<Context>().getString(R.string.base_url))
            .addCallAdapterFactory(get<CoroutineCallAdapterFactory>())
            .addConverterFactory(get<GsonConverterFactory>())
            .build()

有什么建议吗?谢谢

【问题讨论】:

  • 您发送到APIJSON 有效负载是什么样的?

标签: json spring kotlin gson retrofit


【解决方案1】:

您正在使用 @Query 注释,这意味着您的 Thing 将被序列化为 String 并作为 URL 中的查询参数传递。

您希望使用 @Body 注释,它将Thing 对象序列化为 JSON 并将其添加到 POST 正文。

此答案将为您提供有关如何使用该注释的更多详细信息:https://stackoverflow.com/a/21423093/5577048

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 2018-07-15
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多