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:

{"@password":["p","r","o","f","u","s","e","l","y"],"@password_checked":["_","_","_","_","u","_","_","_","_"],"@chances":8,"@picked_letters":["u","a"]}


My methods to serialize and unserialize come from https://www.sitepoint.com/choosing-right-serialization-format/ and they look like this:

require 'json'

module BasicSerializable

@@serializer = JSON

def serialize
obj = {}
instance_variables.map do |var|
obj[var] = instance_variable_get(var)
end

@@serializer.dump obj
end

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


My code to unserialize look like this

file = File.new(game_to_load, '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
serialized_object
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