将类实例另存为JSON

时间:2018-12-31 15:38:54

标签: r json s4

问题

我正在与RC各种定制类一起进行项目。我想在程序末尾保存某些类实例,以便将它们导出到数据库。我尝试使用jsonlite::toJSON(account),但收到错误消息

  

错误:S4类的任何方法:BankAccount

课程

我有以下课程

BankAccount <- setRefClass('BankAccount', 
                       fields  = list(
                         balance = 'numeric',
                         ledger = 'data.frame'
                         ),
                       methods = list(
                         deposit  = function (x) {
                           x <- max(x,0)
                           balance <<- balance + x
                           ledger <<- data.frame(
                             Date   = c(ledger$Date, as.character(Sys.time())),
                             Type   = c(ledger$Type, 'Deposit'),
                             Amount = c(ledger$Amount, x),
                             stringsAsFactors = FALSE
                           )
                          },
                         withdraw = function (x) {
                           x <- max(x,0)
                           balance <<- balance - x
                           ledger <<- data.frame(
                             Date   = c(ledger$Date, as.character(Sys.time())),
                             Type   = c(ledger$Type, 'Withdrawal'),
                             Amount = c(ledger$Amount, x),
                             stringsAsFactors = FALSE
                           )
                         }
                       ))

实例

这是该类的一个实例

account <- BankAccount$new(balance = 100)
account$deposit(1000)
Sys.sleep(5)
account$withdraw(97.89)
account
Reference class object of class "BankAccount"
Field "balance":
[1] 1002.11
Field "ledger":
                 Date       Type  Amount
1 2018-12-31 16:21:20    Deposit 1000.00
2 2018-12-31 16:21:26 Withdrawal   97.89

JSON

现在我想将其另存为以下形式的JSON文件(JSON中可能有错字-不太熟悉格式)

{
  "balance": "double",
  "ledger": {
    "Date": "string",
    "Type": "string",
    "Amount": "double"
  }
}

PS

我也尝试了不使用字段ledger(属于data.frame类),但是仍然无法正常工作。


修改

这是jsonlite::serializeJSON(account)

的输出
{"type":"S4","attributes":{".xData":{"type":"environment","attributes":{},"value":{}}},"value":{"class":"BankAccount","package":".GlobalEnv"}} 

如您所见,它似乎仅保存有关类BankAccount的信息,而不保存有关实例account的信息(缺少余额等)。

1 个答案:

答案 0 :(得分:0)

这是一种解决方法(如@StefanF所示)。可以向类添加方法

# converts to JSON
toJSON = function (prettifyy = TRUE) {
           instanceJSON <- jsonlite::toJSON(list(balance = balance,ledger  = ledger))
           if (prettifyy) instanceJSON <- jsonlite::prettify(instanceJSON)
           instanceJSON
         }
# saves as .json, e.g. path = 'C:/Test/instance.json'
saveJSON = function (path) {
             instanceJSON <- toJSON()
             writeLines(instanceJSON, path)
           }

该解决方案并不理想

  • 由于需要指定应合并哪些字段,因此需要一点工作
  • 同样,如果BankAccount的字段属于MyClass类(另一个自定义类),那么您需要指定MyClass的哪些字段相关或创建一个{{ 1 {}和toJSON