开发者

Ruby on Rails serialize and then deserialize the same object in JSON

I have spent days on this trying out all the JSON libraries including the JSON gem, Yajl-ruby, ActiveSupport::JSON and nothing can do this simple task:

user = User.find(1)
json = user.to_json
user2 = json.as_json # OR json.from_json 
                     # OR JSON.parse(json) 
                     # OR Yajl::Parser.parse(json)
                     # OR ActiveSupport::JSON.decode(json)

When I try to use the deserialized JSON data to create a new User, I get one of the following errors:

User.new(Yajl::Parser.parse(json))  
# ActiveRecord::UnknownAttributeError: unknown attribute: j开发者_开发技巧son_class

User.new(json.as_json)
# NoMethodError: undefined method `stringify_keys!' for #<String:0xb6de4318>

User.new(JSON.parse(json))
# NoMethodError: undefined method `stringify_keys!' for #<User:0xb6dc7470>

User.new(ActiveSupport::JSON.decode(json))
# NoMethodError: undefined method `stringify_keys!' for #<User:0xb6da3764>

This is so easy to do with YAML using to_yaml and from_yaml. Why can't to_json produce the kind of JSON that from_json could convert back to a ruby object?

Edit: I am using Rails 2.3.8, although I have tried 2.3.5 and 3.0.0. Also, I am using the json-rpc plugin to create a JSON-RPC service, although the same problem persists without the plugin.


json = Episode.first.to_json
dec = ActiveSupport::JSON.decode json
Episode.new dec['episode']

Works for me in Rails 3.0.1. In your examples you didn't take out actual attributes dict from wrapper dict after you converted JSON back to Ruby. You should try

User.new(ActiveSupport::JSON.decode(json)['user'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜