【发布时间】:2020-10-29 17:45:28
【问题描述】:
我是 kotlin 和 android 开发的新手。我目前正在尝试在我的本地服务器中获取对 django REST-API 的 POST 请求。我将 Retrofit 2 和 Gson 用于 http 请求和 JSON。
我有一个用于 POST 正文 (DataPost) 的类,如下所示:
class DataPost(_type: String, _attributes: Item) {
@SerializedName("type")
var type: String? = null
@SerializedName("attributes")
var attributes: Item? = null
}
class Item(_userId: Int, _dbId: Int, _title: String, _body: String){
@SerializedName("userdId")
var userdId: Int = 0
@SerializedName("dbId")
var dbId: Int = 0
@SerializedName("title")
var title: String? = null
@SerializedName("body")
var body: String? = null
companion object {
fun className(): String {return "Item"}
}
}
当我初始化它并尝试序列化它并通过以下方式将其记录到 JSON 时:
var item: Item = Item(1,2,"Shiee","shie body")
var data: DataPost = DataPost("Item", item)
Log.i(TAG_LOGS, Gson.toJson(data))
我刚刚得到这个输出:
{}
并且控制台/日志中没有错误。所以我假设它没有因为嵌套对象而对它的属性进行序列化,但无论如何,我可能是错的。为什么我的 DataPost 对象返回一个空 JSON?
编辑:预期的 JSON:
{
"type": "Item",
"attributes": {
"userdId": 1,
"dbId": 2,
"title": "Shiee",
"body": "shiee body"
}
}
【问题讨论】: