Search code examples
jsoncrystal-lang

Object to_json with all properties


I have some classes that sended to a API thru HTTP and I need to be exported to json with all properties (including nils).

I have a class like this:

class Customer

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

  def initialize @token
  end
end

When I create a instance of Customer and export to json I retrieve unexpected result.

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

How to force to to_json function to export porperties class totally?


Solution

  • Use 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"}