I've JSON data like:
{
"peopleA": "nnll",
"peopleB": "ihyt",
"peopleC": "udr",
"peopleD": "vhgd",
"peopleE": "llll"
}
There're thousands of data like that, basically what I wanna to do is read the JSON file, and fetch the relate info, like: input peopleC
, return udr
.
Trying to use some online solution, I got
struct Welcome: Codable {
let peopleA, peopleB, peopleC, peopleD: String
let peopleE: String
}
I know I can refactor the JSON file to:
{
"candidates": [
{
"name": "peopleA",
"info": "nnll"
},
{
"name": "peopleB",
"info": "ihyt"
},
{
"name": "peopleC",
"info": "udr"
}
]
}
And get the related Swift struct:
struct Welcome: Codable {
let candidates: [Candidate]
}
// MARK: - Candidate
struct Candidate: Codable {
let name, info: String
}
I'm just wondering if maybe we could make it work in Swift without postprocessing the json file?
CodePudding user response:
You can simply decode it as a dictionary. Then you can map your dictionary into your array of Candidate structures if you would like to:
struct Welcome: Codable {
let candidates: [Candidate]
}
struct Candidate: Codable {
let name, info: String
}
let js = """
{
"peopleA": "nnll",
"peopleB": "ihyt",
"peopleC": "udr",
"peopleD": "vhgd",
"peopleE": "llll"
}
"""
do {
let dictionary = try JSONDecoder().decode([String: String].self, from: Data(js.utf8))
let welcome = Welcome(candidates: dictionary.map(Candidate.init))
print(welcome)
} catch {
print(error)
}
This will print:
Welcome(candidates: [Candidate(name: "peopleA", info: "nnll"), Candidate(name: "peopleC", info: "udr"), Candidate(name: "peopleB", info: "ihyt"), Candidate(name: "peopleE", info: "llll"), Candidate(name: "peopleD", info: "vhgd")])