Railsの標準機能で、JSONをrubyオブジェクトへとシリアライズする。
Rails製APIでよく使われるのに情報が少ないのでメモ
from_jsonとは?
from_json(json, include_root = include_root_in_json)
modelのattributesをJSON文字列からセットする。
selfをreturnする。
使用例
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
もし与えられたJSON文字列が、root nodeを持っていた場合。
第二引数にtrueを渡すことで、root nodeを排除してシリアライズ可能
json = { person: { name: 'bob', age: 22, awesome: true } }
person = Person.new
person.from_json(json, true)
person.name # bob
person.age # 22
参考
https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html