Skip to content

Instantly share code, notes, and snippets.

@allolex
Created April 14, 2014 15:04
Show Gist options
  • Save allolex/10656276 to your computer and use it in GitHub Desktop.
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
#!/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