【问题标题】:Ruby on Rails JSON.parse(object.to_json) doesn't return the original objectRuby on Rails JSON.parse(object.to_json) 不返回原始对象
【发布时间】:2010-11-15 19:16:09
【问题描述】:

似乎有这样的对象:

#<Course id: 1, name: "Targeting Triple Negative Breast Cancer", description: nil, disclosure: nil, created_at: "2010-11-11 14:43:31", updated_at: "2010-11-11 14:43:31", picture: nil, course_reference_id: nil, authors: "Lisa A. Carey, M.D.", volumn_number: nil, publication_date: nil, expiration_date: nil, credits: 1, featured: false>

我应该能够做到JSON.parse(course.to_json),但是当我尝试这样做时,我得到的不是返回原始对象,而是 Course.new(具有 nil 属性的对象)的等价物。

当我course.to_json 时,我得到:

"{\"attributes\":{\"name\":\"Targeting Triple Negative Breast Cancer\",\"expiration_date\":null,\"created_at\":\"2010-11-11 14:43:31\",\"featured\":\"0\",\"publication_date\":null,\"updated_at\":\"2010-11-11 14:43:31\",\"id\":\"1\",\"disclosure\":null,\"volumn_number\":null,\"credits\":\"1\",\"authors\":\"Lisa A. Carey, M.D.\",\"course_reference_id\":null,\"description\":null,\"picture\":null},\"json_class\":\"Course\",\"attributes_cache\":{}}"

但是当我做JSON.parse(course.to_json) 我得到:

#<Course id: nil, name: nil, description: nil, disclosure: nil, created_at: nil, updated_at: nil, picture: nil, course_reference_id: nil, authors: nil, volumn_number: nil, publication_date: nil, expiration_date: nil, credits: nil, featured: false>

我使用的是 Rails 2.3.5,并且使用其他对象得到相同的结果。

【问题讨论】:

    标签: ruby-on-rails ruby json


    【解决方案1】:

    要序列化/反序列化对象,请使用#to_json#from_json。不要尝试直接解析 JSON 字符串。

    json = Course.new(...).to_json
    Course.new.from_json(json)
    

    还请注意,您应避免直接致电JSON.parse。请改用ActiveSupport::JSON 网桥。

    【讨论】:

    • 当我尝试得到ActiveRecord::UnknownAttributeError: unknown attribute: json_class
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2017-07-02
    • 1970-01-01
    • 2018-02-11
    • 2011-07-05
    • 2013-06-15
    • 1970-01-01
    相关资源
    最近更新 更多