4

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?

anonR
  • 849
  • 7
  • 26
  • It would be easier to help you, if you provided a [reproducible example](http://stackoverflow.com/q/5963269/4303162). Post a piece of code that produces exactly the output that you already show. For this example, you could do `toJSON(fromJSON('{"speech":["aa"],"source":["bb"],"displayText":["cc"]}'), auto_unbox = TRUE)` to get rid of the square brackets. – Stibu Jan 31 '17 at 20:21
  • Added the example – anonR Feb 01 '17 at 05:07

2 Answers2

8

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"}
anonR
  • 849
  • 7
  • 26
4

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.

asachet
  • 6,620
  • 2
  • 30
  • 74
theEricStone
  • 301
  • 1
  • 7