LoginSignup
4

More than 5 years have passed since last update.

RubyでStructをJSONでserialize, deserializeする

Last updated at Posted at 2016-09-02

イマイチやり方がわからなかったのでメモ

参考
- https://github.com/flori/json/blob/master/tests/json_addition_test.rb

宣言

id, nameをattributeにもつStructの例

require 'json/add/core'

class User < Struct.new(:id,:name)
  def self.json_create(o)
    new(*o['v'])
  end
end

Serialize

json = JSON.generate(User.new(1, "ninja"))
# => '{"json_class":"User","v":[1,"ninja"]}'

Deserialize

user = JSON.parse(json, create_additions: true)
# => #<struct User id=1, name="ninja">

簡単で便利だ。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4