2017-09-13 37 views
2

我有一些类通过HTTP发送到API,我需要导出到与所有属性(包括nils)的JSON。对象to_json与所有属性

我有这样一个类:

class Customer 

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

    def initialize @token 
    end 
end 

当我创建的客户和出口实例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功能完全出口调性质类?

回答

4

使用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"}