Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R管道工JSON序列化程序自动取消绑定_Json_R_Plumber - Fatal编程技术网

R管道工JSON序列化程序自动取消绑定

R管道工JSON序列化程序自动取消绑定,json,r,plumber,Json,R,Plumber,按照页面上的示例进行操作 我将myfile.R编写为 #* @post /test test <- function(){ list(speech='aa',source='bb',displayText='cc') } 但我想去掉方括号。在简单的toJSON调用中,可以使用auto_unbox=TRUE来完成,但在plumber中如何实现呢。 如何编写自定义序列化程序并在上述代码中使用它?我计算了添加自定义序列化程序的过程。 假设我们想为JSON创建一个自定义序列化程序,并将其命名为“

按照页面上的示例进行操作

我将myfile.R编写为

#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}
但我想去掉方括号。在简单的toJSON调用中,可以使用auto_unbox=TRUE来完成,但在plumber中如何实现呢。
如何编写自定义序列化程序并在上述代码中使用它?

我计算了添加自定义序列化程序的过程。 假设我们想为JSON创建一个自定义序列化程序,并将其命名为“custom_JSON” myfile.R将是

#* @serializer custom_json
#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}
水管工提供了一个开箱即用的设备
unbox-djson
is

只需在端点上使用
@serializer unbxedjson
注释


您还可以将默认序列化程序设置为
plumber::serializer\u unbox\u json

,如果您提供了。发布一段代码,该代码精确地生成您已经显示的输出。对于本例,您可以执行
toJSON(fromJSON(“{”speech:[“aa”],“source:[“bb”],“displayText:[“cc”]}”),auto_unbox=TRUE)
来去掉方括号。添加了已在
plumber::serializer_unbox_json
中提供的示例。请看另一个答案。
curl -XPOST 'localhost:8000/test
-> {"speech":["aa"],"source":["bb"],"displayText":["cc"]}
#* @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)
curl -XPOST 'localhost:8000/test
-> {"speech":"aa","source":"bb","displayText":"cc"}