gpt4 book ai didi

Swift 中的 JSON 错误

转载 作者:行者123 更新时间:2023-11-30 10:03:03 26 4
gpt4 key购买 nike

我是 Swift 和 API 编程新手,遇到以下错误:

uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]

这是导致此错误的行:

print(json[“totalPostsByUser”])

有关更多上下文,这是更完整的代码示例:

let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let httpResponse = response as? NSHTTPURLResponse
var err: NSError?

if httpResponse!.statusCode == 201 {
if error == nil {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
let jsonData: NSData = jsonStr!.dataUsingEncoding(NSUTF8StringEncoding)!
do {
if let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(responseString)
print(json["totalPostsByUser"])
totalPostsByUser = (json["totalPostsByUser"] as? Int)!
}
} catch let parseError {
}
}
}
}

最佳答案

我认为你需要用下面的代码替换一些代码,

if let json: NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary
{
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(responseString)
//print(json["totalPostsByUser"])
print(json.valueForKey("totalPostsByUser"))
//totalPostsByUser = (json["totalPostsByUser"] as? Int)!
}

将任何对象转换为 MutableDictionary,这样可以很容易地从键中提取值。

希望这对您有帮助。

关于Swift 中的 JSON 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428561/

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