【问题标题】:How to flatten a JSON response when using ActiveResource?使用 ActiveResource 时如何展平 JSON 响应?
【发布时间】:2014-07-10 08:24:38
【问题描述】:

我有一个 API 和一个客户端应用程序,并且我正在使用带有 ActiveResource 的 Rails。

我有一个继承自 ActiveResource::BaseRecruiter 模型

假设我在客户端写:

dave = Recruiter.new(email: "email@recruiter.com", password: "tyu678$--è", full_name:      "David Blaine", company: "GE") 
dave.save

我发送的请求格式如下:

{"recruiter":{
    "email": "email@recruiter.com",
    "password": "tyu678$--è",
    "full_name": "David Blaine",
    "company": "GE"
    }
}

我从 API 获得的 Json 响应格式如下:

   {"recruiter":{
    "email": "email@recruiter.com",
    "password": "tyu678$--è",
    "full_name": "David Blaine",
    "company": "GE",
    "foo": "bar"
    },
    "app_token":"ApfXy8YYVtsipFLvJXQ"
}

问题在于,这将允许我使用 dave.app_token 访问应用令牌,但我不能例如写入 dave.foo,这会引发错误。

有没有办法将响应展平或递归读取它,以便我可以访问我的所有实例的属性,同时保持 API 响应的格式不变?

【问题讨论】:

标签: ruby-on-rails json api activeresource recursive-datastructures


【解决方案1】:

查看整个ActiveResource 过程,您可以覆盖Recruiter 模型中的load 方法。

我刚刚在 #HACK 部分添加了代码,它“扁平化”了您的属性。

def load(attributes, remove_root = false, persisted = false)
  raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
  @prefix_options, attributes = split_options(attributes)

  # HACK
  if !attributes[:app_token].nil?
    attributes[:recruiter]["app_token"] = attributes[:app_token]
    attributes = attributes[:recruiter]
  end
  # /HACK

  if attributes.keys.size == 1
    remove_root = self.class.element_name == attributes.keys.first.to_s
  end

  attributes = ActiveResource::Formats.remove_root(attributes) if remove_root

  attributes.each do |key, value|
    @attributes[key.to_s] =
    case value
    when Array
      resource = nil
      value.map do |attrs|
        if attrs.is_a?(Hash)
          resource ||= find_or_create_resource_for_collection(key)
          resource.new(attrs, persisted)
        else
          attrs.duplicable? ? attrs.dup : attrs
        end
      end
    when Hash
      resource = find_or_create_resource_for(key)
      resource.new(value, persisted)
    else
      value.duplicable? ? value.dup : value
    end
  end
  self
end

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2021-04-11
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多