问题
Is there a JSON DOM that can read any JSON, regardless of type, and store it into something like a Dictionary hierarchy?
Consider this JSON and code...
var jsonData = """
{
"type":"ListWrapper",
"objectData": {
"label":"SuperItems",
"items":[
{
"value":"First"
},
{
"value":"Second"
},
{
"value":"Third"
},
{
"value":"Fourth"
}
]
}
}
""".data(using:.utf8)!
Here's the first part of what we're trying to do. (Note: This doesn't actually work.)
class TestObject : Codable {
var name:String?
var childObject:Data? // <-- This is the 'wishful' part
}
do{
let testObject = try JSONDecoder().decode(TestObject.self, from:jsonData)
processTestObject(testObject)
}
catch let error {
print(error.localizedDescription)
}
Now somewhere else in the application, we have this defined (Note it matches the object stored in 'objectData' above) and we're trying to do this...
class ListWrapper : Codable {
var label:String?
var items:[ListItem]?
}
class ListItem : Codable {
var value:String?
}
do{
switch testObject.type{
case "ListWrapper":
var listWrapper = try JSONDecoder().decode(ListWrapper.self, from:testObject.objectData)
processList(listWrapper)
case "Foo":
var listWrapper = try JSONDecoder().decode(Foo.self, from:testObject.objectData)
processFoo(foo)
}
}
catch let error {
print(error.localizedDescription)
}
Note: Yes, we know we can encode the JSON in 'objectData' and store it as a string, but we're trying to leave the JSON as-is.
One approach would be to write a custom deserializer for TestObject
but we'd have to tell it all the possible types we're looking for. We can do that, but I was hoping to make it a 'dumb' object that just stores the JSON as data or something similar. So is this possible?
来源:https://stackoverflow.com/questions/59794057/is-it-possible-to-read-a-json-sub-object-directly-as-a-json-dom-object-or-data-o