Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

safely attempt S3 dispatch #433

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Package: jsonlite
Version: 1.8.8
Version: 1.8.9
Title: A Simple and Robust JSON Parser and Generator for R
License: MIT + file LICENSE
Depends: methods
Expand Down
41 changes: 28 additions & 13 deletions R/asJSON.ANY.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,34 @@ setMethod("asJSON", "ANY", function(x, force = FALSE, ...) {
} else {
stop("No method for S4 class:", class(x))
}
} else if (length(class(x)) > 1) {
# If an object has multiple classes, we recursively try the next class. This is
# S3 style dispatching that doesn't work by default for formal method definitions
# There should be a more native way to accomplish this
return(asJSON(structure(x, class = class(x)[-1]), force = force, ...))
} else if (isTRUE(force) && existsMethod("asJSON", class(unclass(x))[1])) {
# As a last resort we can force encoding using the unclassed object
return(asJSON(unclass(x), force = force, ...))
} else if (isTRUE(force)) {
}

## walk the s3 class chain (if any):
if (length(class(x)) > 1) {
for (cls in class(x)[-1]) {
f <- getMethod("asJSON", cls, optional = TRUE)
if (!is.null(f)) return(f(x, ...))
}
}

## fallback class:
if (isTRUE(force)) {
f <-
tryCatch({
getMethod("asJSON", class(unclass(x))[1], optional = TRUE) ## unclass() can err, hence tryCatch()
}, error = function(e) NULL)
if (!is.null(f)) return(f(x, ...))
}

msg <- sprintf("No method asJSON S3 class: %s", paste0(class(x), collapse = ","))

## final fallback -- encode NULL and warn:
if (isTRUE(force)) {
warning(msg)
return(asJSON(NULL))
warning("No method asJSON S3 class: ", class(x))
} else {
# If even that doesn't work, we give up.
stop("No method asJSON S3 class: ", class(x))
}

## give up.
stop(msg)
})

Loading