Skip to content

Instantly share code, notes, and snippets.

@andypetrella
Created August 3, 2018 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andypetrella/e1d8e8ef44304345ed698740fb75fc73 to your computer and use it in GitHub Desktop.
Save andypetrella/e1d8e8ef44304345ed698740fb75fc73 to your computer and use it in GitHub Desktop.
fix swagger R json manipulations
FWIW, I know it's dirty/nasty :-/
#' R6_list Class
#'
#' @field entries
#'
#' @importFrom R6 R6Class
#' @export
R6_list <- R6::R6Class(
'R6_list',
public = list(
`entries` = NULL,
initialize = function(...){
entries <- list(...)
self$`entries` <- `entries`
}
)
)
dam.convert <- function(o) {
v = o
if (inherits(o, "R6_list")) {
# Some fields... are checked to be R6 instances although sometimes they aren't
# e.g. like using Option[Map[String, List[String]]] in Scala...
v = dam.convert(o$entries)
} else if (R6::is.R6(o)) {
v = r6.to.list(o)
}
# not in `else if` because we may process the previous results!!!
if (is.list(v)) {
v = lapply(v, function(i) {
dam.convert(i)
})
}
v
}
r6.to.list <- function(o, o.class = get(class(o)), o.fields = names(o.class$public_fields)) {
o.return = list();
for(f in o.fields) {
v = dam.convert(o[[f]])
o.return[[f]] = v
}
o.return
}
r6.to.jsonstring <- function(o) {
jsonlite::toJSON(r6.to.list(o), auto_unbox=TRUE)
}
r6.to.json <- function(o) {
jsonlite::fromJSON(r6.to.jsonstring(o))
}
The above functions would have to replace `toJSONString` and `toJSON`in generated classes:
If original class would look like the following:
```R
R6_test <- R6::R6Class(
'R6_test',
public = list(
`x` = NULL,
initialize = function(x){
self$`x` <- `x`
},
toJSON = function() {
NULL
}
)
)
```
Then we would replace like the following
```R
R6_test$public_methods$toJSON = function() { r6.to.json(self) }
tt <- R6_test$new(x=list(a= 1.1, b="ok"))
```
tt.toJSON()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment