ToTenMilan ToTenMilan - 4 years ago 107
JSON Question

Ruby - Why unserialization from JSON is outputting Array instead of my class?

I'm doing a simple hangman game in Odin Project with an option to save and load game.

I have already serialized my class in JSON and save it to file which contents look like this:


My methods to serialize and unserialize come from and they look like this:

require 'json'

module BasicSerializable

@@serializer = JSON

def serialize
obj = {} do |var|
obj[var] = instance_variable_get(var)

@@serializer.dump obj

def unserialize(string)
obj = @@serializer.parse(string)
obj.keys.each do |key|
instance_variable_set(key, obj[key])

My code to unserialize look like this

file =, 'r')
serialized_object = file.gets # serialized_object is the file from above
p @password.class #=> Password
@password = unserialize(serialized_object)
p @password.class #=> Array
p @password #=> ["@password", "@password_checked", "@chances", "@picked_letters"]

The problem is that I can't figure out why unserialization of
is outputting me the Array. How to make it to output my class with the state of object saved in a file mentioned in the beginning?

Answer Source

You didn't call unserialize on the @password object, so it's going to be called on the current object. You didn't show what that is, but I guess it's an Array.

Instead you want @password.unserialize.

Some notes...

Since unserialize changes the object and blows away existing data, it should probably be unserialize!.

Note that Ruby already has a Marshal class to do serialization and deserialization. It's in a binary format, not JSON.

Storing your passwords as clear text is a really bad idea. Passwords should never, ever, EVER be stored, only their hashes. Good hashing means if the password file is stolen, there's additional hurdles for the attacker to jump. If you do it right, they're nigh unbreakable.

See Salted Password Hashing - Doing it Right.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download