Swift JSON解析并打印数组中的指定值

时间:2017-07-03 20:15:56

标签: ios json swift xcode swift3

您好我正在尝试从某个JSON API获取数据。我可以从API中获取所有值的快照,如下所示。但我无法设法在变量中放置一个特定行。这是我得到的JSON表单。我想打印“描述”值。可以有人帮我这个吗? The API result which I get

而Hier是我的代码:

func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }


    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}

3 个答案:

答案 0 :(得分:2)

首先,array 不是数组,而不是AnyObject,它是Swift 3中的[String:Any]字典。

let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)

我不知道为什么所有教程都建议.mutableContainers作为选项。这可能在Objective-C中很有用,但在Swift中完全没有意义。省略参数。

items的对象是一个字典数组(同样,Swift 3中未指定的JSON类型是Any)。使用重复循环来获取所有description值并且你有将字典的所有值从Any向下转换为预期类型。

if let items = dictionary["items"] as? [[String:Any]] {
   for item in items {
       if let description = item["Description"] as? String {
          print(description)
       }
   }
}

答案 1 :(得分:0)

看起来item是一个需要循环的数组。下面是一些示例代码,但我想提醒您,此代码未针对您的数据进行测试。

if let items = array["items"] as? [[String: AnyObject]] {
    for item in items {
        if let description = item["Description"] as? String{
            print("Description: \(description)")
        }
    }
}

上面的代码或其中的一些变体应该让您走上正确的轨道。

答案 2 :(得分:0)

使用SwiftyJSON,它就像json["items"][i].arrayValue一样简单,返回和带有项值的数组或json["items"][i]["description"].stringValue来获取行中的字符串