How to do Ruby object serialization using JSON

前端 未结 3 1400
面向向阳花
面向向阳花 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:33

    Use Marshal, PStore, or another Ruby solution for non-JSON objects

    One might reasonably wonder why a completely reflective language like Ruby doesn't automate JSON generation and parsing of arbitrary classes.

    However, unless you stick to the JSON types, there is no place to send or receive the JSON objects except to another running Ruby. And in that case, I suspect that the conventional wisdom is "forget JSON, use a native Ruby interface like the core class Marshal.

    So, if you are really sending those objects to PHP or something non-Ruby, then you should create directly JSON-supported Ruby data structures using Array and the like, and then you will have something that JSON.generate will directly deal with.

    If you just need serialization it's possible you should use Marshal or PStore.

    Update: Aha, ok, try this:

    module AutoJ
      def auto_j
        h = {}
        instance_variables.each do |e|
          o = instance_variable_get e.to_sym
          h[e[1..-1]] = (o.respond_to? :auto_j) ? o.auto_j : o;
        end
        h
      end
      def to_json *a
        auto_j.to_json *a
      end
    end
    

    If you then include AutoJ in each of your classes, it should DTRT. In your example this results in

    {
      "a": {
        "string_field1": "aa",
        "string_field2": "bb"
      },
      "b": {
        "int_field3": 123,
        "string_field4": "dd"
      }
    }
    

    You might want to change the auto_j method to return h.values instead of just h, in which case you get:

    [
      ["aa", "bb"],
      [123, "dd"]
    ]
    

提交回复
热议问题