JSON Ruby 中的反序列化

JSON Deserialization in Ruby

在 Ruby 中是否有 JSON 等价于 Java 的 Google JSON 的反序列化。无需为每个 class 定义任何自定义序列化程序或反序列化程序,可以编写一行代码将 JSON 字符串转换为自定义 Java class,如图所示在这里下。

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

要实现这一点,不需要在地址 class 中放置任何 annotations/interfaces,也不需要为我们需要反序列化的每个 class 编写单独的反序列化器实用程序。这使得从第三方库 deserialize/serialize classes 变得非常容易。关于是否序列化空值/包含/排除某些属性等有很多选择。我正在寻找这样一个通用的 JSON 从和到自定义对象 serialization/deserialization 实用程序 Ruby .我是 Ruby.

的新手

参考:

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

您可以使用 JSON 模块将其转换为哈希:

require 'json'

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

如果你想把它转换成一个"structured"对象,你可以使用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)

如果您并不总是知道 JSON 键,OpenStruct 可能会帮助您,因为它会动态创建一个对象。

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