跳至内容 跳至搜索

Active Model JSON 序列化器

方法
A
F
包含的模块

实例公共方法

as_json(options = nil)

返回一个表示模型的哈希。可以通过options传递一些配置。

选项include_root_in_json控制as_json的顶层行为。如果为trueas_json将发出一个以对象类型命名的单个根节点。include_root_in_json选项的默认值为false

user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#     "created_at" => "2006-08-01T17:27:133.000Z", "awesome" => true}

ActiveRecord::Base.include_root_in_json = true

user.as_json
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

此行为也可以通过将:root选项设置为true来实现,如下所示:

user = User.find(1)
user.as_json(root: true)
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

如果您愿意,也可以将:root设置为自定义字符串键,如下所示:

user = User.find(1)
user.as_json(root: "author")
# => { "author" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

如果没有任何options,返回的Hash将包含模型的所有属性。

user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true}

:only:except选项可用于限制包含的属性,其工作方式类似于attributes方法。

user.as_json(only: [:id, :name])
# => { "id" => 1, "name" => "Konata Izumi" }

user.as_json(except: [:id, :created_at, :age])
# => { "name" => "Konata Izumi", "awesome" => true }

要包含模型上某些方法调用的结果,请使用:methods

user.as_json(methods: :permalink)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "permalink" => "1-konata-izumi" }

要包含关联,请使用:include

user.as_json(include: :posts)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
#                   { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }

二级和更高阶关联也适用

user.as_json(include: { posts: {
                           include: { comments: {
                                          only: :body } },
                           only: :title } })
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
#                     "title" => "Welcome to the weblog" },
#                   { "comments" => [ { "body" => "Don't think too hard" } ],
#                     "title" => "So I was thinking" } ] }
# File activemodel/lib/active_model/serializers/json.rb, line 96
def as_json(options = nil)
  root = if options && options.key?(:root)
    options[:root]
  else
    include_root_in_json
  end

  hash = serializable_hash(options).as_json
  if root
    root = model_name.element if root == true
    { root => hash }
  else
    hash
  end
end

from_json(json, include_root = include_root_in_json)

JSON字符串设置模型attributes。返回self

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:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name            # => "bob"
person.age             # => 22
person.awesome         # => true

include_root的默认值为false。如果给定的JSON字符串包含一个单个根节点,您可以将其更改为true

json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
person = Person.new
person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name                  # => "bob"
person.age                   # => 22
person.awesome               # => true
# File activemodel/lib/active_model/serializers/json.rb, line 146
def from_json(json, include_root = include_root_in_json)
  hash = ActiveSupport::JSON.decode(json)
  hash = hash.values.first if include_root
  self.attributes = hash
  self
end