无法解析JSON

时间:2017-12-10 13:51:30

标签: json swift

我在Swift中解析一些JSON时遇到问题。我无法获得它返回的errors变量nil。我认为它应该是一本字典? 下面是我在控制台中打印的API返回的JSON。

{
    error = "{\"name\":[\"The name has already been taken.\"],\"email\":[\"The email has already been taken.\"]}";
    success = 0;
}

这是Swift代码。

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

    if let parseJSON = json {
        print(parseJSON)
        let success = parseJSON["success"] as? Int

        if(success == 1) {
            let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);

            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
                (action) in
                self.dismiss(animated: true, completion: nil)
            }

            myAlert.addAction(okAction);
            self.present(myAlert, animated: true, completion: nil)
        } else {
            let errors = parseJSON["error"] as? NSDictionary
            if(errors != nil){
                print("NOT NIL")
                // self.displayAlertMessage()
            }
        }
    }
} catch{
    print(error)
}

修改 这是使用下面的David代码打印的JSON。 这是打印到控制台的parseJSON。

["error": {"name":["The name has already been taken."],"email":["The email has already been taken."]}, "success": 0]

以下是戴维斯更新代码的完整方法。

let task = URLSession.shared.dataTask(with: request) { (theData: Data?, response: URLResponse?, theError: Error?) in

    DispatchQueue.main.async
        {

            //spinningActivity!.hide(true)

            if theError != nil {
                self.displayAlertMessage(theError!.localizedDescription)
                return
            }

            do {
                guard let parseJSON = try JSONSerialization.jsonObject(with: theData!) as? [String:Any] else {return}
                //print(parseJSON)
                let success = parseJSON["success"] as? Int
                if(success == 1) {
                    let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);

                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
                        (action) in
                        self.dismiss(animated: true, completion: nil)
                    }

                    myAlert.addAction(okAction);
                    self.present(myAlert, animated: true, completion: nil)
                } else {
                    guard let errors = parseJSON["success"] as? Int else {return}
                    print(errors)
                }
            } catch{
                print(error)
            }



    }

}

task.resume()

1 个答案:

答案 0 :(得分:0)

您的代码有几个问题可能不会直接导致问题,但这些问题都是不良做法。不要在Swift中使用IcookieVisitor,在解码JSON响应时使用NSDictionary并且不要使用[String:Any],因为它在.mutableContainers中没有效果,可变性在声明变量时由Swiftlet关键字确定。

此外,不要将控制台打印作为JSON响应,在您的问题中包含实际的JSON响应,因为Swift的var语句不会产生有效的JSON。< / p>

print

输出:

  

&#34; [&#34;名称&#34;:名称已被拍摄。,&#34;电子邮件&#34;:&lt; __ NSSingleObjectArrayI 0x608000019f80&gt;(\ n已收到电子邮件。\ n )\ n] \ n上&#34;