我定义了数据类,配置了 gson 并创建了 rout 来处理 post 请求,如下所示:
data class PurchaseOrder(val buyer: String, val seller: String,
val poNumber: String, val date: String,
val vendorReference: String)
install(ContentNegotiation) {
gson {
setDateFormat(DateFormat.LONG)
setPrettyPrinting()
}
post("/purchaseOrder"){
val po = call.receive<PurchaseOrder>()
println("purchase order: ${po.toString()}")
call.respondText("post received", contentType =
ContentType.Text.Plain)
以下 JSON 在 POST 请求中发送
{
"PurchaseOrder" : {
"buyer": "buyer a",
"seller": "seller A",
"poNumber": "PO1234",
"date": "27-Jun-2018",
"vendorReference": "Ref1234"
}
}
输出显示所有空值。
purchase order: PurchaseOrder(buyer=null, seller=null, poNumber=null,
date=null, vendorReference=null)
从 call.request.receiveChannel() 读取数据确实显示正确的 JSON。所以我正在接收数据,但 call.receive() 似乎没有产生预期的结果。
手动获取 JSON 并尝试按如下方式创建 PurchaseOrder 但没有运气:
val channel = call.request.receiveChannel()
val ba = ByteArray(channel.availableForRead)
channel.readFully(ba)
val s = ba.toString(Charset.defaultCharset())
println(s) // prints JSON
val gson = Gson()
val po = gson.fromJson(s, PurchaseOrder::class.java)
println("buyer = ${po.buyer}" //prints null