Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Deserialization in Ruby

Is there a JSON Deserialization equivalent of Java's Google JSON in Ruby. With-out the necessity of defining any custom serializer or deserializer for each class, one can write a one-line code to convert JSON string into custom Java class as shown here under.

Address address=gson.fromJson(addressJsonStringForm, Address.class);

To accomplish this , one need-not put any annotations/interfaces in Address class nor write separate Deserializer utility for every class that we need to deserialize. This makes it very easy to deserialize/serialize classes from third party libraries. There are quite a lot of options on whether to serialize nulls / include /exclude certain attributes etc. I 'm looking for such a versatile JSON from and to custom object serialization/deserialization utility in Ruby. I 'm new to Ruby.

Reference:

https://dzone.com/articles/deserializing-json-java-object

like image 482
Vineel Avatar asked Dec 22 '18 20:12

Vineel


2 Answers

You can convert it into a Hash using the JSON module:

require 'json'

hash = JSON.parse('{"age":18, "name":"Vinicius"}')
hash["age"]
=> 18

If you want to convert it to a "structured" object, you can use OpenStruct:

require 'json'
require 'ostruct'

person = JSON.parse('{"age":18, "name":"Vinicius"}', object_class: OpenStruct)
person.name
=> "Vinicius"

An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby's metaprogramming to define methods on the class itself. (docs)

OpenStruct may help you if you don't always know the JSON keys, as it dynamically creates an object.

like image 111
Vinicius Brasil Avatar answered Nov 10 '22 03:11

Vinicius Brasil


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
like image 4
Oshan Wisumperuma Avatar answered Nov 10 '22 02:11

Oshan Wisumperuma