In order for the JSON library to be available, you may have to install libjson-ruby from the package manager.
To use the json library:
require 'json'
To convert an object to JSON (these three methods are equivalent):
JSON.dump object #returns a JSON string JSON.generate object #returns a JSON string object.to_json #returns a JSON string
To convert JSON text to an object (these two methods are equivalent):
JSON.load string #returns an object JSON.parse string #returns an object
It will be a little harder for objects from your own classes. For the next class, to_json will create something like "\"#<A:0xb76e5728>\"" .
class A def initialize a=[1,2,3], b='hello' @a = a @b = b end end
This is probably undesirable. To effectively serialize your object as JSON, you must create your own to_json method. To do this, it is useful to use the from_json class method. You can expand your class as follows:
class A def to_json {'a' => @a, 'b' => @b}.to_json end def self.from_json string data = JSON.load string self.new data['a'], data['b'] end end
You can automate this by inheriting the 'JSONable' class:
class JSONable def to_json hash = {} self.instance_variables.each do |var| hash[var] = self.instance_variable_get var end hash.to_json end def from_json! string JSON.load(string).each do |var, val| self.instance_variable_set var, val end end end
Then you can use object.to_json to serialize to JSON and object.from_json! string object.from_json! string to copy the saved state that was saved as the JSON string for the object.
david4dev Dec 16 '10 at 19:42 2010-12-16 19:42
source share