R 管道工 JSON 序列化程序 auto_unbox

R plumber JSON serializer auto_unbox

按照页面上的示例进行操作 http://plumber.trestletech.com/

我把myfile.R写成了

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

我 运行 上面的管道工代码将 int 转换为 API

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

现在,当我对它执行 POST 请求时,我得到

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

但我希望删除方括号。在简单的 toJSON 调用中,可以使用 auto_unbox=TRUE 来完成,但我如何在水管工中完成。 如何编写自定义序列化程序并在上面的代码中使用它?

我想出了添加自定义序列化程序的过程。 假设我们想为 JSON 创建一个自定义序列化程序并将其命名为 "custom_json" myfile.R 会是

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

虽然 运行 水管工代码会变成

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)

现在,当我使用

对其执行 POST 请求时
curl -XPOST 'localhost:8000/test
-> {"speech":"aa","source":"bb","displayText":"cc"}

管道工提供 number of serializers out of the box. unboxedJSON is one of them

只需在您的端点上使用 @serializer unboxedJSON 注释。

您还可以将默认序列化程序设置为 plumber::serializer_unboxed_json