parse json to object ruby

后端 未结 5 461
囚心锁ツ
囚心锁ツ 2020-12-24 07:13

I looked into different resources and still get confused on how to parse a json format to a custom object, for example

class Resident
  attr_accessor :phone,         


        
5条回答
  •  感动是毒
    2020-12-24 07:46

    If you're using ActiveModel::Serializers::JSON you can just call from_json(json) and your object will be mapped with those values.

    class Person
      include ActiveModel::Serializers::JSON
    
      attr_accessor :name, :age, :awesome
    
      def attributes=(hash)
        hash.each do |key, value|
          send("#{key}=", value)
        end
      end
    
      def attributes
        instance_values
      end
    end
    
    json = {name: 'bob', age: 22, awesome: true}.to_json
    person = Person.new
    person.from_json(json) # => #
    person.name # => "bob"
    person.age # => 22
    person.awesome # => true
    

提交回复
热议问题