I want to struct my JSON array in Swift so I can use it, but everything I try throws an error. This is the JSON I'm working with:
[
{
"id": 15438,
"date": "2019-05-07T03:36:51",
"date_gmt": "2019-05-07T00:36:51",
"type": "post",
"title": {
"rendered": "Title Here"
}
}
]
And this is the code I'm using:
struct getTitle: Decodable {
let title: [Title]
}
struct Title: Decodable {
let rendered: String?
}
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "URL HERE"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let titleresult = try JSONDecoder().decode(getTitle.self, from: data)
print(titleresult)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
}
The error it's throwing is:
Error serializing json: typeMismatch(Swift.Dictionary<Swift.String,
Any>, Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary<String, Any> but found an array
instead.", underlyingError: nil))
I already tried using
JSONDecoder().decode([getTitle].self, from: data)
to make it an array, but that throws the same error but turned around. It expected an array but found a dictionary.
I'm not sure what the problem is here. I already tried following multiple guides but they all result in the same thing. It's probably something with the struct I'm doing wrong but I don't know what.