Swift: How to declare a node type which match any arbitrary JSON?

Viewed 35

Following code loads JSON from a file, and expecting it has an xsd type.

struct xsd: Decodable {
    var name: String
    var address: String
}

do {
    if let jsonURL = Bundle.main.url(forResource: "user", withExtension: "json") {
        let jsonData = try Data(contentsOf: jsonURL)
        let jsonDecoder = JSONDecoder()
        let persons = try jsonDecoder.decode(xsd.self, from: jsonData)
        print(persons)
        let ii = 7
    }
} catch  {
    
}

What if xsd would be more dynamic and it would match any arbitrary JSON in the file?


How can I define a type which would represent a JSON attribute-key pairs? It should be a recursive structure.

Here guy define one for HTML. https://theswiftdev.com/result-builders-in-swift/

I would do the same for JSON.

This is a Node for HTML:

public struct Node {

    public enum `Type` {
        case standard     // <name>contents</name>
        case comment      // <!-- contents -->
        case empty        // <name>
        case group        // *group*<p>Lorem ipsum</p>*group*
    }

    public let type: `Type`
    public let name: String?
    public let contents: String?

    public init(type: `Type` = .standard,
                name: String? = nil,
                contents: String? = nil) {
        self.type = type
        self.name = name
        self.contents = contents
    }
}
0 Answers
Related