问题
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