【问题标题】:How should look link the json response so that ActiveResource may generate a DateTime object from a date?应该如何链接 json 响应,以便 ActiveResource 可以从日期生成 DateTime 对象?
【发布时间】:2013-07-25 15:14:37
【问题描述】:

我有一个问题对象,其中包含 created_at 属性。当我找到问题时,我会从 REST 服务中取回 created_at,但 Activeresource 不会将日期字符串转换为 DateTime。

Question.find(1)
/questions/1.json

Question.find(1).created_at.class
=> String

Json 响应应该采用哪种格式,以便 ActiveResource 将其转换为 DateTime?

如果不可能,我该怎么办?

【问题讨论】:

    标签: ruby-on-rails json rest activeresource


    【解决方案1】:

    根据this presentation 中的幻灯片#14,您可以在config/initializers/active_resource.rb 中执行此操作:

    ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
    ActiveSupport.parse_json_times = true
    

    【讨论】:

      【解决方案2】:

      JSON 将始终是一个字符串,因为这就是它将数据作为字符串化对象传递的方式。如果要将其转换为日期/时间对象,则需要在服务器端对其进行解析。

      Time.parse 应该可以解决问题

      http://ruby-doc.org/stdlib-2.0/libdoc/time/rdoc/Time.html#method-c-parse

      【讨论】:

      • 但我需要 json 结构,因为我的休息服务在 perl 中而不是在 Rails 中。
      猜你喜欢
      • 1970-01-01
      • 2014-01-19
      • 2022-12-09
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多