gpt4 book ai didi

json - 解析 JSON 时遇到问题

转载 作者:行者123 更新时间:2023-11-30 11:56:41 25 4
gpt4 key购买 nike

我在 Swift 中解析一些 JSON 时遇到问题。我无法获取返回 nil 的 errors 变量。我想这应该是一本字典吧?下面是从我的 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]

这是我的完整方法,其中包含 Davids 更新的代码。

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()

最佳答案

您的代码存在一些问题,这些问题可能不会直接导致问题,但却是不好的做法。不要在 Swift 中使用 NSDictionary,在解码 JSON 响应时使用 [String:Any] 并且不要使用 .mutableContainers 因为它没有在 Swift 中,可变性由声明变量时的 letvar 关键字决定。

此外,请勿将控制台打印包含为 JSON 响应,而应在问题中包含实际的 JSON 响应,因为 Swift 的 print 语句不会生成有效的 JSON。

let apiErrorResponse = """
{
"error": {
"name": "The name has already been taken.",
"email": ["The email has already been taken."]
},
"success": 0
}
"""
func handleApiErrorResponse(){
do {
guard let parseJSON = try JSONSerialization.jsonObject(with: apiErrorResponse.data(using: .utf8)!) as? [String:Any] else {return}
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["error"] as? [String:Any] else {return}
print(errors)
}
} catch{
print(error)
}
}

handleApiErrorResponse()

输出:

"["name": The name has already been taken., "email": <__NSSingleObjectArrayI 0x608000019f80>(\nThe email has already been taken.\n)\n]\n"

关于json - 解析 JSON 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com