Ruby objects and JSON serialization (without Rails)

前端 未结 11 1968
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 03:32

I\'m trying to understand the JSON serialization landscape in Ruby. I\'m new to Ruby.

Is there any good JSON serialization options if you are not working with Rails?

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:24

    Since I searched a lot myself to serialize a Ruby Object to json:

    require 'json'
    
    class User
      attr_accessor :name, :age
    
      def initialize(name, age)
        @name = name
        @age = age
      end
    
      def as_json(options={})
        {
          name: @name,
          age: @age
        }
      end
    
      def to_json(*options)
        as_json(*options).to_json(*options)
      end
    end
    
    user = User.new("Foo Bar", 42)
    puts user.to_json #=> {"name":"Foo Bar","age":42}
    

提交回复
热议问题