R plumber JSON serializer auto_unbox

北慕城南 提交于 2019-12-12 16:17:36

问题


Following the example on the page http://plumber.trestletech.com/

I wrote myfile.R as

#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}

And I ran the plumber code on it to convert int into an API

library(plumber)
r <- plumb("~/Work/myfile.R")
r$run(port=8000)

And Now when I perform an POST request on it using I get

curl -XPOST 'localhost:8000/test
-> {"speech":["aa"],"source":["bb"],"displayText":["cc"]}

But I want the square brackets to be removed. In simple toJSON calls it can be done using auto_unbox=TRUE but how can I do it in plumber. How can I write a custom serializer and use it in the above code?


回答1:


I figured the process to add custom serializers. Let's say we want to make a custom serializer for JSON and name it "custom_json" myfile.R would be

#* @serializer custom_json
#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}

And while running plumber code it would go as

library(plumber)
library(jsonlite)

custom_json <- function(){
  function(val, req, res, errorHandler){
    tryCatch({
      json <- jsonlite::toJSON(val,auto_unbox=TRUE)

      res$setHeader("Content-Type", "application/json")
      res$body <- json

      return(res$toResponse())
    }, error=function(e){
      errorHandler(req, res, e)
    })
  }
}

addSerializer("custom_json",custom_json)
r <- plumb("~/Work/myfile.R")
r$run(port=8000)

And Now when I perform an POST request on it using I get

curl -XPOST 'localhost:8000/test
-> {"speech":"aa","source":"bb","displayText":"cc"}



回答2:


Plumber provides a number of serializers out of the box. unboxedJSON is one of them.

Simply use the @serializer unboxedJSON annotation on you endpoint.

You can also set the default serializer to be plumber::serializer_unboxed_json.



来源:https://stackoverflow.com/questions/41965032/r-plumber-json-serializer-auto-unbox

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