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.