eco-friendly
metaprogramming
Doodle::JSON adds the #to_json and from_json methods. To use it you must have the json gem installed.
Assuming the following definition:
require 'doodle' require 'doodle/json' class Name < Doodle has :value, :kind => String end class Age < Doodle has :value, :kind => Integer end class Person < Doodle has Name has Age end
You can output JSON using object.to_json:
person = Person do name "Corum" age 999 end puts person.to_json
to get the output:
{"json_class":"Person","data":{"name":{"json_class":"Name","data":{"value":"Corum"}},"age":{"json_class":"Age","data":{"value":999}}}}
and load from a JSON source using Doodle.from_json:
person = Doodle.from_json(<<EOT) { "json_class": "Person", "data": { "name": { "json_class": "Name", "data": { "value":"Corum" } }, "age": { "json_class": "Age", "data": { "value":999 } } } } EOT pp person # >> #<Person:0x1148538 # >> @age=#<Age:0x114b0f8 @value=999>, # >> @name=#<Name:0x114e3fc @value="Corum">>
If you want basic output without all the json_class and data members, use to_hash before the to_json:
{"name":{"value":"Corum"},"age":{"value":999}}
Also, remember that doodles can be initialized from hashes, so the following is also possible:
json = '{"name": "Corum", "age": 999}' person = Person.from_json(json) pp person # >> #<Person:0x114ec08 # >> @age=#<Age:0x11482e0 @value=999>, # >> @name=#<Name:0x114c610 @value="Corum">>