I am trying to implement a new protocol Codable, so I added Codableto my structure, but I am stuck in JSON decoding .
Here is what I had before:
Struct -
struct Question {
var title: String
var answer: Int
var question: Int
}
Customer -
...
guard let data = data else {
return
}
do {
self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]
questionItems.forEach {
let item = Question(title: $0["title"] as! String,
answer: $0["answer"] as! Int,
question: $0["question"] as! Int)
questionData.append(item)
}
} catch {
print("error")
}
Here is what I have, except that I cannot determine the part of the decoder:
Struct -
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
Customer -
...
let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
} else {
print("Not working")
}
He prints "Doesn't work," because I can't get past the part decoder.decode. Any ideas? Print any additional code as needed, thanks!
EDIT:
JSON API Example:
{
"themes": [
{
"answer": 1,
"question": 44438222,
"title": "How many letters are in the alphabet?"
},
{
"answer": 0,
"question": 44438489,
"title": "This is a random question"
}
]
}
If I print self.jsonResponse, I get the following:
Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
"answer" = 7;
"question" = 7674790;
title = "This is the title of the question";
},
{
"answer_" = 2;
"question" = 23915741;
title = "This is the title of the question";
}
My new code is:
struct Theme: Codable {
var themes : [Question]
}
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
...
if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
print("decoded:", decoded)
} else {
print("Not working")
}