Created
April 14, 2014 15:04
-
-
Save allolex/10656276 to your computer and use it in GitHub Desktop.
Example of how to serialise and deserialise Structs in Ruby using the Standard Library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'json' | |
require 'json/add/struct' | |
require 'awesome_print' | |
Serial = Struct.new(:foo, :bar, :baz) | |
s = Serial.new('this','that','the other') | |
puts 'The Struct instance' | |
ap s | |
# { | |
# :foo => "this", | |
# :bar => "that", | |
# :baz => "the other" | |
# } | |
serialised = s.as_json | |
puts 'Serialised' | |
ap serialised | |
# { | |
# "json_class" => "Serial", | |
# "v" => [ | |
# [0] "this", | |
# [1] "that", | |
# [2] "the other" | |
# ] | |
# } | |
json_string = serialised.to_json | |
puts 'Stringified' | |
ap json_string | |
# "{\"json_class\":\"Serial\",\"v\":[\"this\",\"that\",\"the other\"]}" | |
deserialised = Serial.json_create( JSON.parse(json_string) ) | |
puts 'Deserialised' | |
ap deserialised | |
# { | |
# :foo => "this", | |
# :bar => "that", | |
# :baz => "the other" | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment