gson 如何在Ktor中接收JSON对象?

hxzsmxv2  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(124)

我已经定义了数据类,配置了gson并创建了路由器来处理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)

在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
nlejzf6q

nlejzf6q1#

问题是您已经将json Package 在"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请求不变,你有两个选择。
1.一个自定义的gson序列化程序,它要求将请求 Package 在PurchaseOrder中。
1.一个 Package 类,如下所示:

class PurchaseOrderWrapper(
    val purchaseOrder: PurchaseOrder
)

那么你就可以这样接收:

call.receive<PurchaseOrderWrapper>().purchaseOrder

相关问题