diff options
author | Florian Frank <flori@ping.de> | 2017-06-21 11:51:46 +0200 |
---|---|---|
committer | Florian Frank <flori@ping.de> | 2017-06-21 11:51:46 +0200 |
commit | 05604654b4706a5a1153c4085bbd1b3548cc247f (patch) | |
tree | 4a9f286e1599556496b922448501f1b68b52f17a | |
parent | 4753d185eb7d74806c43716db846febf33b9cd23 (diff) | |
parent | 3d69dad9142bfa9678d590e0842f8d8c880c2ec5 (diff) | |
download | json-05604654b4706a5a1153c4085bbd1b3548cc247f.tar.gz |
Merge branch 'master' of storage.gate.ping.de:/git/json
-rw-r--r-- | README.md | 38 |
1 files changed, 21 insertions, 17 deletions
@@ -179,14 +179,14 @@ should return a JSON object (a hash converted to JSON with `#to_json`) like this (don't forget the `*a` for all the arguments): ```ruby - class Range - def to_json(*a) - { - 'json_class' => self.class.name, # = 'Range' - 'data' => [ first, last, exclude_end? ] - }.to_json(*a) - end - end +class Range + def to_json(*a) + { + 'json_class' => self.class.name, # = 'Range' + 'data' => [ first, last, exclude_end? ] + }.to_json(*a) + end +end ``` The hash key `json_class` is the class, that will be asked to deserialise the @@ -200,20 +200,24 @@ called with the JSON object converted to a Ruby hash. So a range can be deserialised by implementing `Range.json_create` like this: ```ruby - class Range - def self.json_create(o) - new(*o['data']) - end - end +class Range + def self.json_create(o) + new(*o['data']) + end +end ``` Now it possible to serialise/deserialise ranges as well: ```ruby - json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] - # => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]" - JSON.parse json - # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10] +json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] +# => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]" +JSON.parse json +# => [1, 2, {"a"=>3.141}, false, true, nil, 4..10] +json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] +# => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]" +JSON.parse json, :create_additions => true +# => [1, 2, {"a"=>3.141}, false, true, nil, 4..10] ``` `JSON.generate` always creates the shortest possible string representation of a |