2

I've the following Problem:

I'm using the opencpu package to provide my R Package as a web application. In my package I created a RefClass lets call that

.A <- setRefClass(
  ".A",
  fields = c(
    id = "integer",
    text = "character"
  )
)

plus a constructor function:

A <- function(id,text ){return(.A(id,text))}

and on top I wrote a method "toJSON" for the class and also provided an S4 method like this:

.A$methods(
  toJSON = function(){
     return(sprintf('{\"id\": %s, \"text\": %s}',id,text))
})

  setMethod("toJSON", c(".A"),function(x,...){
    x$toJSON()
  })

So far everthing is fine. When I install the package and run opencpu, I can call the A method without a problem: (POST with parameters e.g.: {id: 123, text: "Hallo World"})

SERVERADRESS/ocpu/library/PACKAGENAME/R/A

But when I want the returned value to be directly converted into JSON I get the following error:

No method for S4 class:.A

A look at the opencpu site, tells that the procedure which is called in this case is:

library(jsonlite)
args <- fromJSON('{"id": 123, "text": "Hallo World"}')
output <- do.call(PKGNAME::A,args)
toJSON(output)

However this runs fine if I run it in a regular R session. But the error becomes reproducable if I change the last line from toJSON(output) to jsonlite::toJSON(output) Hence I think this might be the problem and I was wundering if I can add my "toJSON" S4 method with signature ".A" to the Namespace of "jsonlite" within my package?

Any Ideas?

HolgerBarlt
  • 307
  • 1
  • 18
  • 1
    You cannot add custom `toJSON` methods. Why not design your R function such that it returns a regular R list that can easily be serialized? Then it will work out of the box. – Jeroen Ooms Nov 21 '18 at 13:14
  • Thanks for the comment. This is only a minimum example to demonstrate the problem. The package is quite complex and is not only supposed to serve the web application. But if there is no way to expand the toJSON method I probably Need to come up with some work around. Thanks! – HolgerBarlt Nov 21 '18 at 13:21

0 Answers0