How to Do Ruby Object Serialization Using JSON

How to do Ruby object serialization using JSON

Use Marshal, PStore, or another Ruby solution for non-JSON objects

One might reasonably wonder why a completely reflective language like Ruby doesn't automate JSON generation and parsing of arbitrary classes.

However, unless you stick to the JSON types, there is no place to send or receive the JSON objects except to another running Ruby. And in that case, I suspect that the conventional wisdom is "forget JSON, use a native Ruby interface like the core class Marshal.

So, if you are really sending those objects to PHP or something non-Ruby, then you should create directly JSON-supported Ruby data structures using Array and the like, and then you will have something that JSON.generate will directly deal with.

If you just need serialization it's possible you should use Marshal or PStore.

Update: Aha, ok, try this:

module AutoJ
def auto_j
h = {}
instance_variables.each do |e|
o = instance_variable_get e.to_sym
h[e[1..-1]] = (o.respond_to? :auto_j) ? o.auto_j : o;
end
h
end
def to_json *a
auto_j.to_json *a
end
end

If you then include AutoJ in each of your classes, it should DTRT. In your example this results in

{
"a": {
"string_field1": "aa",
"string_field2": "bb"
},
"b": {
"int_field3": 123,
"string_field4": "dd"
}
}

You might want to change the auto_j method to return h.values instead of just h, in which case you get:

[
["aa", "bb"],
[123, "dd"]
]

Serialize Ruby object to JSON and back?

The easiest way is to make a to_json method and a json_create method. In your case, you can do this:

class CrawlStep
# Insert your code here (attr_accessor and initialize)

def self.json_create(o)
new(*o['data'])
end

def to_json(*a)
{ 'json_class' => self.class.name, 'data' => [id, name, next_step] }.to_json(*a)
end
end

Then you serialize by calling JSON.dump(obj) and unserialize with JSON.parse(obj). The data part of the hash in to_json can be anything, but I like keeping it to the parameters that new/initialize will get. If there's something else you need to save, you should put it in here and somehow parse it out and set it in json_create.

How to serialize/deserialize ruby hashes/structs with objects as keys to json

JSON only allows strings as object keys. For this reason to_s is called for all keys.

You'll have the following options to solve your issue:

  1. The best option is changing the data structure so it can properly be serialized to JSON.

  2. You'll have to handle the stringified key yourself. An Hash produces a perfectly valid Ruby syntax when converted to a string that can be converted using Kernel#eval like Andrey Deineko suggested in the comments.

    result = json.transform_keys { |key| eval(key) }
    # json.transform_keys(&method(:eval)) is the same as the above.

    The Hash#transform_keys method is relatively new (available since Ruby 2.5.0) and might currently not be in you development environment. You can replace this with a simple Enumerable#map if needed.

    result = json.map { |k, v| [eval(k), v] }.to_h

    Note: If the incoming JSON contains any user generated content I highly sugest you stay away from using eval since you might allow the user to execute code on your server.

Ruby serialize struct with JSON

In this case, person.to_json is not doing what you expect.

When you require 'json', the JSON library inserts a #to_json method on Object that is a fallback if there's no specialized #to_json method provided elsewhere. This inserted method is basically the same as calling #to_s#to_json on an object.

In the case of your Person class here, #to_s outputs the standard Object#to_s, which, by default, doesn't provide a string parseable by the JSON library.

However, Struct does provide a #to_h method that can be used to convert that struct to a Hash, and Hash is (upon requiring the JSON library) aware of how to generate a JSON parseable output.

So simply changing:

json = Person.new('Adam', 19).to_json
puts json

to:

person = Person.new('Adam', 19)
puts person.to_h.to_json

will do what you expect.

(An aside, I would actually recommend implementing #to_json on the Person class directly as calling #to_h#to_json violates the Law of Demeter.)

JSON Deserialization in Ruby

jsonapi-rb

    DeserializablePost.call(json_hash)

roar

    song = Song.new(title: "Medicine Balls")
SongRepresenter.new(song).from_json('{"title":"Linoleum"}')
song.title #=> Linoleum

Netflix - fast_jsonapi

    json_string = MovieSerializer.new(movie).serialized_json


Related Topics



Leave a reply



Submit