I have a data structure that uses the Set class from the Ruby Standard Library. I'd like to be able to serialize my data structure to a JSON string.
By default, Set serializes as an Array:
>> s = Set.new [1,2,3]
>> s.to_json
=> "[1,2,3]"
Which is fine until you try to deserialize it.
So I defined a custom to_json method:
class Set
def to_json(*a)
{
"json_class" => self.class.name,
"data" => {
"elements" => self.to_a
}
}.to_json(*a)
end
def self.json_create(o)
new o["data"]["elements"]
end
end
Which works great:
>> s = Set.new [1,2,3]
>> s.to_json
=> "{\"data\":{\"elements\":[1,2,3]},\"json_class\":\"Set\"}"
Until I put the Set into a Hash or something:
>> a = { 'set' => s }
>> a.to_json
=> "{\"set\":[1,2,3]}"
Any idea why my custom to_json doesn't get called when the Set is nested inside another object?