4

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: nil, 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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When I try that I get ActiveRecord::UnknownAttributeError: unknown attribute: json_class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.