【问题标题】:Rails to_json response converting datetime to unixtimestampRails to_json 响应将日期时间转换为 unixtimestamp
【发布时间】:2014-04-14 10:13:13
【问题描述】:

我使用 rails 创建了一个 REST API,并使用 .to_json 将 API 输出转换为 json 响应。例如。 @response.to_json

响应中的对象包含 created_at 和 updated_at 字段,都是 Datetime

在 JSON 响应中,这两个字段都被转换为字符串,这比 unixtimestamp 解析成本更高。

有没有一种简单的方法可以将 created_at 和 updated_at 字段转换为 unixtimestamp 而不必遍历 @response 中的整个对象列表?

[更新] 如果它是一个简单的 .to_json,danielM 的解决方案就可以工作。但是,如果我有一个 .to_json(:include=>:object2),则 as_json 将导致响应不包含 object2。对此有何建议?

【问题讨论】:

    标签: ruby-on-rails json datetime unix-timestamp


    【解决方案1】:

    在您的响应模型上定义一个 as_json 方法。每当您将响应模型的实例作为 JSON 返回到您的 REST API 时,就会运行此操作。

    def as_json(options={})
        {
            :id => self.id,
            :created_at => self.created_at.to_time.to_i,
            :updated_at => self.updated_at.to_time.to_i
        }
    end
    

    您也可以显式调用 as_json 方法来取回哈希并在其他地方使用它。

    hash = @response.as_json
    

    Unix 时间戳参考:Ruby/Rails: converting a Date to a UNIX timestamp

    编辑:as_json 方法也适用于关系。只需将键添加到函数返回的哈希中。这也将运行关联模型的 as_json 方法。

    def as_json(options={})
        {
            :id => self.id,
            :created_at => self.created_at.to_time.to_i,
            :updated_at => self.updated_at.to_time.to_i,
            :object2 => self.object2,
            :posts => self.posts
        }
    end
    

    此外,您可以将参数传递给该方法以控制如何构建哈希。

    def as_json(options={})
        json = {
            :id => self.id,
            :created_at => self.created_at.to_time.to_i,
            :updated_at => self.updated_at.to_time.to_i,
            :object2 => self.object2
        }
    
        if options[:posts] == true
            json[:posts] = self.posts
        end
        json
    end
    
    hash = @response.as_json({:posts => true})
    

    【讨论】:

    • danielM,我注意到如果我执行 to_json(:include => :object2) 之类的操作,这种方法不起作用,包含被省略。我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多