I’m reading a JSON document (and then putting it in a sqlite database). The document is much more complicated than I need to actually track, so I’m trying to figure out how to do two things:
First question:
There is a list of associated objects (an array of strings) that is buried deep in nested JSON objects that I otherwise don’t need to extract. For example, imagine the document looks like…
{
"id": 12345,
"name": "Paul",
"complicated": {
"object": {
"nested": {
"deeply": [
"a",
"b",
"c"
]
}
}
}
}
And my class looks like:
class Thing
include JSON::Serializable
property id : Int64
property name : String
property nested_list : Array(String)
# ...
end
Since the array is nested more than one object deep, is there any way to use JSON::Serializable? Or am I going to have to write a custom from_json
function?
Or… is there a way I can have JSON::Serializable trigger on the “complicated” key, and call a custom method to decode it?
Second question:
I would really like my class to have a property, raw_json
, which is a String containing the full raw JSON from which it was decoded.
Is this possible with JSON::Serializable in any way?
Using the example above:
class Thing
include JSON::Serializable
property id : Int64
property name : String
property nested_list : Array(String)
property raw_json : String
end
json_string="{"id":12345,"name":"Paul","complicated":{"object":{"nested":{"deeply":["a","b","c"]}}}}"
thing=Thing.from_json(json_string)
thing.raw_json == json_string # => true
I know that’s likely to be difficult; I know instead that I can make it nilable, and assign it after creating the object. For example:
class Thing
def self.new(json_string : String)
thing = Thing.from_json(json_string)
thing.raw_json=json_string
thing
end
end
But it would be nice if I could do it inside the Thing.from_json
class method, since then I would be able to parse it when it’s embedded in other documents.
I hope these questions are clear enough that someone can make some suggestions. The first question is definitely more important than the second…
Thanks!
Paul