Swift 4 Codable解码json

时间:2017-06-07 21:45:35

标签: swift codable

我正在尝试实施新的Copy协议,因此我将Paste添加到我的结构中,但坚持解码JSON

这是我以前的所作所为:

结构 -

Codable

客户 -

...

Codable

这就是我现在所拥有的,除了我无法找出解码器部分:

结构 -

struct Question {
    var title: String
    var answer: Int
    var question: Int
}

客户 -

...

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")
}

它打印“不工作”,因为我无法通过struct Question: Codable { var title: String var answer: Int var question: Int } 部分。有任何想法吗?将根据需要发布任何额外的代码,谢谢!

编辑:

API JSON示例:

let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
    // Can't get past this part
} else {
    print("Not working")
}

如果我打印decoder.decode我就明白了:

{
  "themes": [
    {
      "answer": 1,
      "question": 44438222,
      "title": "How many letters are in the alphabet?"
    },
    {
      "answer": 0,
      "question": 44438489,
      "title": "This is a random question"
    }
  ]
 }

我的新代码:

self.jsonResponse

...

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";
}

3 个答案:

答案 0 :(得分:8)

如果您的JSON具有结构

{"themes" : [{"title": "Foo", "answer": 1, "question": 2},
             {"title": "Bar", "answer": 3, "question": 4}]}

您需要themes对象的等效项。添加此结构

struct Theme : Codable {
    var themes : [Question]
}

现在您可以解码JSON:

if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}

隐含地解码包含Question个对象。

答案 1 :(得分:1)

您收到此错误是因为您的JSON可能是这样构建的:

{
  "themes": [
    { "title": ..., "question": ..., "answer": ... },
    { "title": ..., "question": ..., "answer": ... },
    { ... }
  ],
  ...
}

但是,您编写的代码需要顶级[Question]。您需要的是具有themes属性[Question]的不同顶级类型。解码该顶级类型后,您的[Question]将针对themes密钥进行解码。

答案 2 :(得分:0)

Hello @all我已经为Swift 4添加了JSON编码和解码的代码。

请使用链接here