2017-07-03 9 views
0

こんにちは、特定のJSON APIからデータを取得しようとしています。下に示すAPIのすべての値のスナップショットを取得できます。しかし、私は変数に特定の行を置くことはできません。これはJSON形式です。私は "説明"の値を印刷したい。誰かがこれで私を助けることができますか? The API result which I getSwift JSONの解析と配列からの指定値の出力

そしてハイアー私のコードです:

func apiRequest() { 
    let config = URLSessionConfiguration.default 
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D" 
    let password = "[email protected]#" 
    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) 
    } 
} 

答えて

2

すべてarrayの第一は、ないアレイとないAnyObjectあり、それはすべてのチュートリアルは、オプションとして.mutableContainersを提案する理由を私は知らないスウィフト3の[String:Any]

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

ある辞書です。これはObjective-Cで役に立ちますが、Swiftでは全く意味がありません。パラメータを省略します。

キーitemsのためのオブジェクトが再び、スウィフト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) 
     } 
    } 
} 
+0

から文字列を取得する項目の値を使用したリターンと配列としてjson["items"][i].arrayValueまたはjson["items"][i]["description"].stringValueと同じくらい簡単だろう!ノウ私はそれを得る。あなた本当に私を助けました! –

0

のアイテムのように見えるがループスルーする必要が配列です。ここにいくつかのサンプルコードがありますが、私はこのコードがあなたのデータについてテストされていないことを警告したいと思います。

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

上記のコードまたはその変形は、正しい軌道上にあるはずです。

0

SwiftyJSONを使用して、たくさんありがとう行