【问题标题】:convert json data to array in swift3在swift3中将json数据转换为数组
【发布时间】:2017-08-14 09:10:23
【问题描述】:

我想将我的 json 响应转换为一个数组,但它不起作用,我收到一个错误,提示我数组中的项目为零

func getcomments(){
    RestApiManager.sharedInstance.getComments(TUTORIAL_ID: id){
        response in
        let comments = JSON(response)

        for item in comments.array!{
            let comment = Comment(memail:  String(describing: item["email"]), mcomment:  String(describing: item["comment"]), mcomment_date:  String(describing: item["comment_date"]), manswer:  String(describing: item["answer"]), manswer_date:  String(describing: item["answer_date"]))
            self.comments.append(comment)
        }
    }
}

这是我的 json 响应:

   [{
        "email": "-",
        "comment": "\u0627\u0632 \u0627\u067e\u0644\u06cc\u06a9\u06cc\u0634\u0646 \u062e\u0648\u0628\u062a\u0648\u0646 \u0645\u0645\u0646\u0648\u0646\u0645",
        "comment_date": "2017-07-15 19:30:00",
        "answer": null,
        "answer_date": null
    },
    {
        "email": "S.M_Emamian@yahoo.com",
        "comment": "salam",
        "comment_date": "2017-07-11 19:30:00",
        "answer": "\u062a\u0634\u06a9\u0631",
        "answer_date": "2017-07-12 03:50:57"
    }
]

我在这一行得到 nil 错误:

在展开可选值时意外发现 nil

for item in comments.array!

【问题讨论】:

  • 就在这里comments.array! 如果你要敲什么东西,最好确保它不是零。我不认为你可以在这里保证。显然不是,因为它崩溃了。
  • response的类型是什么?如果是字符串则需要使用JSON(parseJSON:)
  • @sweeper 是的,我需要 JSON(parseJSON:) 它可以工作,谢谢
  • @fazed 我作为答案发布。请考虑通过单击该复选标记接受它!

标签: json swift xcode


【解决方案1】:

根据您的评论,response 实际上是一个字符串。因此,您不能只使用init(_:) 创建 JSON。你需要init(parseJSON:)

init(_:) 将只使用该字符串而不是 JSON 对象创建一个 JSON,这显然不是您想要的。 init(parseJSON:) 实际上会解析您的 JSON 字符串并允许您访问不同的键值对。

func getcomments(){
    RestApiManager.sharedInstance.getComments(TUTORIAL_ID: id){
        response in
        let comments = JSON(parseJSON: response)

【讨论】:

    【解决方案2】:

    如果将其解码为结构数组会更容易。

    首先,创建结构体:

    struct Comment: Codable {
      var email: String
      var comment: String
      var comment_date: String
      var answer: String
      var answer_date: String
    }
    

    然后你可以像这样调用 JSON:

    guard let url = Bundle.main.url(forResource: resource, withExtension: "json") else {
        throw Errors.couldNotFindResource
    }
    data = try! JSONDecoder().decode([Comment].self, from: Data(contentsOf: url))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多