How to receive JSON object in Ktor?

爷,独闯天下 提交于 2019-12-12 12:01:26

问题


I have data class defined, configured gson and created rout to handle post request as follows:

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)

the following JSON is sent in POST request

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

The output shows all nulls.

purchase order: PurchaseOrder(buyer=null, seller=null, poNumber=null, 
date=null, vendorReference=null)

Reading data from call.request.receiveChannel() does show correct JSON. So I am receiving the data but call.receive() does not seem to produce expected results.

Got JSON manually and tried to create PurchaseOrder as follows bu no luck:

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:


The problem is that you have wrapped your json in "PurchaseOrder".

If you post this instead:

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

it correctly receives the following:

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

If you want to keep the json request as is, you have 2 options.

  1. A custom gson serializer that expects the request to be wrapped in PurchaseOrder.

  2. A wrapper class like this:

class PurchaseOrderWrapper( val purchaseOrder: PurchaseOrder )

Then you can receive like this: call.receive<PurchaseOrderWrapper>().purchaseOrder



来源:https://stackoverflow.com/questions/51449280/how-to-receive-json-object-in-ktor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!