7

我定义了数据类,配置了 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
4

1 回答 1

4

问题是您已将 json 包装在"PurchaseOrder".

如果您改为发布此内容:

{
    "buyer": "buyer a",
    "seller": "seller A",
    "poNumber": "PO1234",
    "date": "27-Jun-2018",
    "vendorReference": "Ref1234"
}

它正确接收以下内容:

purchase order: PurchaseOrder(buyer=buyer a, seller=seller A, poNumber=PO1234, date=27-Jun-2018, vendorReference=Ref1234)

如果你想保持 json 请求不变,你有 2 个选项。

  1. 一个自定义的 gson 序列化器,它期望请求被包装在PurchaseOrder.

  2. 像这样的包装类:

class PurchaseOrderWrapper(
    val purchaseOrder: PurchaseOrder
)

然后你可以收到这样的:

call.receive<PurchaseOrderWrapper>().purchaseOrder
于 2018-07-21T09:25:43.573 回答