简体   繁体   中英

Swift: How to write JSON as a struct?

I have this very simple JSON file, which looks like this, but how can I write it as a Swift Structure?

Would this be right?

struct SomeName: Codable {
    var action = [String: [String: String]]()
    var trigger = [String: [String: String]]()
}

在此处输入图像描述

You could do something like this.

Firstly I converted the JSON into Data so that it is possible to decode it.

Second as there are two properties in the JSON, action and trigger, I create two nested structs that match the properties. In the second struct Trigger we need to use a custom coding key as Swift uses camelcase by convention, and you cannot use a - in a variable name.

import Foundation

let data = """
[
    {
        "action": {
            "type": "block"
        },
        "trigger": {
            "url-filter": "apple.com"
        }
    }
]
""".data(using: .utf8)!

struct SomeName: Codable {
    
    struct Action: Codable {
        let type: String
    }
    
    struct Trigger: Codable {
        let urlFilter: String
        
        enum CodingKeys: String, CodingKey {
            case urlFilter = "url-filter"
        }
    }
    
    let action: Action
    let trigger: Trigger
}

do {
    let result = try JSONDecoder().decode([SomeName].self, from: data)
} catch {
    print(error)
}


Putting the above code into a Playground, it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM