gpt4 book ai didi

json - Swift 带有带有列表信息的 json 数据

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

我正在制作一个 iOS 应用程序,使用 PHP API 从数据库调用历史信息。

我的 json 输出显示如下:

[{"ID":"6","searchTerm":"Not Responding - Windows 8.1","solutionID":"1","date":"2015-01-26 08:23:34"},
{"ID":"7","searchTerm":"Not Responding - Windows 8.1","solutionID":"1","date":"2015-01-26 08:41:29"},
{"ID":"9","searchTerm":"Windows 8 startup","solutionID":"6","date":"2015-01-26 08:41:29"}]

当 JSON 是单个返回数组时,以下命令有效:

let idusers:NSInteger = jsonData.valueForKey("idusers") as NSInteger

但我找不到任何关于处理这种类型的数据格式的解决方案。任何关于如何读取 JSON 的帮助都会很棒。

仅供引用的是 VC:

 var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

var postLength:NSString = String( postData.length )

var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")


var reponseError: NSError?
var response: NSURLResponse?

var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

if ( urlData != nil ) {
let res = response as NSHTTPURLResponse!;

NSLog("Response code: %ld", res.statusCode);

if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

NSLog("Response ==> %@", responseData);

var error: NSError?

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary


let idusers:NSInteger = jsonData.valueForKey("idusers") as NSInteger

最佳答案

您从 API 获得一个 NSDictionaries 数组,您还需要循环遍历数组中的每个条目,然后获取键的值。

if let jsonArray = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Array<NSDictionary>

关于json - Swift 带有带有列表信息的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28999658/

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