Is it possible to read a JSON sub-object directly as a JSON DOM object or Data or some other generic format?

馋奶兔 提交于 2021-01-28 11:00:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!