如何在Ktor中接收JSON对象?

时间:2018-07-20 19:32:50

标签: kotlin gson ktor

我已经定义了数据类,配置了gson并创建了rout来处理发布请求,如下所示:

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)

在POST请求中发送以下JSON

{
"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

1 个答案:

答案 0 :(得分:1)

问题是您已将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