It seems that with an object like this:
#<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>
I should be able to do JSON.parse(course.to_json)
, but when I try this, instead of returning the original object, I get the equivalent of Course.new (an object with nil attributes).
When I do course.to_json
I get:
"{\"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\":{}}"
But when I do JSON.parse(course.to_json)
I get:
#<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: ni开发者_如何学Gol, publication_date: nil, expiration_date: nil, credits: nil, featured: false>
I am using Rails 2.3.5 and I get the same result with other objects.
To serialize/deserialize the object use #to_json
and #from_json
. Don't try to parse the JSON string directly.
json = Course.new(...).to_json
Course.new.from_json(json)
Also note you should avoid calling JSON.parse
directly. Use ActiveSupport::JSON
bridge instead.
精彩评论