具有所有属性的对象 to_json

Object to_json with all properties

我有一些 classes 通过 HTTP 发送到 API,我需要将所有属性(包括 nils)导出到 json。

我有一个 class 这样的:

class Customer

  JSON.mapping(
    id:    UInt32 | Nil,
    name:  String | Nil,
    email: String | Nil,
    token: String
  )

  def initialize @token
  end
end

当我创建 Customer 的实例并导出到 json 时,我检索到意外结果。

c = Customer.new "FULANITO_DE_COPAS"
puts c.to_json

# Outputs
{"token":"FULANITO_DE_COPAS"}

# I expect
{"id":null,"name":null,"email":null,"token":"FULANITO_DE_COPAS"}

如何强制 to_json 函数完全导出属性 class?

使用emit_null:

class Customer

  JSON.mapping(
    id:    {type: UInt32?, emit_null: true},
    name:  {type: String?, emit_null: true},
    email: {type: String?, emit_null: true},
    token: String
  )

  def initialize(@token)
  end
end

c = Customer.new "FULANITO_DE_COPAS"
c.to_json #=> {"id":null,"name":null,"email":null,"token":"FULANITO_DE_COPAS"}