[colug-432] Ruby de/serialization
Rick Hornsby
richardjhornsby at gmail.com
Tue Jun 16 16:26:29 EDT 2015
I'm working on a Ruby (2.x, I know it matters) app, and one of the things I need is to be able to serialize/deserialize custom objects to/from JSON. I've got the serialization down, that was pretty easy. The deserialization is proving to be a much more difficult beast.
Gist links at the bottom of the message.
There's a couple of specific things I'm having a hard time with. I finally figured out that in my JSON.parse call[1], I have to add ':create_additions => true' otherwise the object won't be reconstituted correctly[2]. From my reading this attribute seems to be required as a result of some kind of an underlying Ruby bug. Am I setting myself up for security issues with this attribute? A more general question, is my whole approach of implementing to_json() and json_create()[3] (or serialization/deserialization) wrong?
Here's the generated json string:
Making a json string from a Song
{"json_class":"Song","data":{"title":"New Title","artist":"Artist 1","album":null,"remarks":null,"url":null}}
And this is the generic object json.Parse provides[4] to my json_create method:
[{"json_class"=>"Song",
"data"=>
{"title"=>"New Title",
"artist"=>"Artist 1",
"album"=>nil,
"remarks"=>nil,
"url"=>nil}}]
I'm not understanding the deserialization very well:
* why the JSON parser gives me back an array (containing a hash) instead of just the hash, forcing me to specify an array index in my json_create method. None of the examples suggested to expect this.
* why the Song initialize method complains if I replace "*args" with 5 distinct arguments ("Wrong number of arguments, 0 for 5") in the method declaration
* Assuming I must use *args, how to handle the previous bullet properly in the initialize method without named arguments. That is, it looks like I'm going to end up accessing the arguments using an array index which seems like a bad way to do it.
I've found a bunch of examples and explanations of serialization/deserialization that got me this far, but nothing I've found is quite a complete example. I got the impression from most that I wouldn't even need a class initialize - the implemented json_create method would magically handle it somehow - which in retrospect seems like a silly assumption on my part.
thanks!
-rick
[1] https://gist.github.com/rjhornsby/968552f86174650d3874#file-songtest-rb-L15
[2] http://stackoverflow.com/a/15165553
[3] https://gist.github.com/rjhornsby/6db2760db605bea6f865
[4] https://gist.github.com/rjhornsby/6db2760db605bea6f865#file-song-rb-L33
Note - This is just example code - I know the accessors need to be cleaned up and handled better to not expose the internals of the class like that.
More information about the colug-432
mailing list