How to do Ruby object serialization using JSON

前端 未结 3 1401
面向向阳花
面向向阳花 2020-12-19 05:08

I have a structure of simple container classes like so (in pseudo ruby):

class A
  attr_reader :string_field1, :string_field2
  ...
end

class B
  attr_reade         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 05:34

    I had the same problem (mainly trying to create JSON strings of arbitrary complexity) rather than parsing them. After looking all over for a non-invasive class that will take a Ruby object (including nested arrays) and marshal it as a JSON string I finally wrote my own simple serialiser. This code also escapes special characters to create valid JSON.

    http://www.keepingmyhandin.com/Downhome/Sketchup/simplejsonserializerrubyimplementation

    All you have to do is:

    json  = JSON.new;
    jsonString = json.marshal(obj); # Where obj is a Ruby object
    

提交回复
热议问题