gpt4 book ai didi

json - Swift 中的远程 json 解析

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

[
-{
valid:"2",
invalid: "1",
pending: "2"
},
-{
valid:"0",
invalid: "1",
pending: "0"
},
-{
valid:"2",
invalid: "1",
pending: "2"
}
]

我正在尝试解析此远程 json 并将数据填充到数组中。我花了几个小时努力找出为什么我的代码不起作用,数组最终总是空的。有人可以告诉我我做错了什么吗?

  var arrayreports : [Report] = []
var report = Report()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let host = appDelegate.host
if(Reachability.isConnectedToNetwork()){

let postEndpoint: String = host+"/api/reportbyworkflow/7"

let session = NSURLSession.sharedSession()
let url = NSURL(string: postEndpoint)!

session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 201 else {


print("Bad thing happened")
return
}

do {


if let ipString = NSString(data:data!, encoding: NSUTF8StringEncoding) {


let jsonDictionary:AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

let json = jsonDictionary as? Array<AnyObject>


for index in 0...json!.count-1 {
let contact : AnyObject? = json![index]
print(contact)

let collection = contact! as! Dictionary<String, AnyObject>
let valid = collection["valid"] as! String
let invalid = collection["invalid"] as! String
let pending = collection["pending"] as! String

report!.valid = Double(Int(valid)!)
report!.invalid = Double(Int(invalid)!)
report!.pending = Double(Int(pending)!)


arrayreports.append(report!)
}

}}


catch {

print("bad things happened")


}



}).resume()

}

最佳答案

如果您的 json 确实是您在此处复制的,则它无效(请在 jsonvalidator.com 上检查)。

所以序列化返回空数组是正常的

关于json - Swift 中的远程 json 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653422/

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