Ruby serializes structure using JSON

I am trying to serialize a simple structure in JSON that works fine, but I cannot force it to instantiate this structure from JSON. This is how I try to do it.

require 'rubygems' require 'json' Person = Struct.new(:name, :age) json = Person.new('Adam', 19).to_json puts json me = JSON.load(json) puts me.name 

And I get the following output:

 "#<struct Person name=\"Adam\", age=19>" /usr/lib/ruby/1.9.1/json/common.rb:148:in `parse': 746: unexpected token at '"#<struct Person name=\"Adam\", age=19>"' (JSON::ParserError) from /usr/lib/ruby/1.9.1/json/common.rb:148:in `parse' from /usr/lib/ruby/1.9.1/json/common.rb:309:in `load' from why.rb:9:in `<main>' 
+6
source share
1 answer

In this case, person.to_json does not do what you expect.

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

In the case of your Person class, here #to_s displays the Object#to_s , which by default does not provide string parsing by the JSON library.

However, Struct provides a #to_h method that can be used to convert this structure to Hash , and Hash (with a JSON library) knows how to generate JSON parsing.

So a simple change:

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

in

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

will do what you expect.

(As an aside, I would recommend implementing #to_json in the Person class directly, since calling #to_h#to_json violates the Law of Demeter .)

+10
source

Source: https://habr.com/ru/post/981952/


All Articles