LoginSignup
0
1

More than 3 years have passed since last update.

ActiveModel::Serializers::JSONのfrom_jsonの使い方を3分で理解。

Last updated at Posted at 2020-05-29

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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1