Reputation: 219
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]]()
}
Upvotes: 0
Views: 476
Reputation: 28539
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.
Upvotes: 1