2017-04-14 135 views
3

所以我一直在試圖整天使用Alomofire 4我的WordPress REST API解析JSON,我已經試過所有我能找到的是/是與我的問題但我仍然不能管理解決我的問題。解析嵌套的JSON與Alamofire 4

我們的目標僅僅是從API執行請求並將其打印出來,從那裏我可以管理,但由於JSON似乎有嵌套的數組/字典,我很難搞清楚要使用什麼。

我的代碼:

Alamofire.request(_newsURL).responseJSON { response in 
     print(response.result) 

     if let json = response.result.value as? [Any] { 

      print("JSON: \(json)") 
     } 

     if let dict = response.result.value as? Dictionary<String, AnyObject>{ 

      print(response.result.value) 

      if let slug = dict["slug"] as? String { 

       self._newsSlug = slug 
      } 

      print("Hello News") 
      print(self._newsURL) 
      print(self._newsSlug) 
     } else { 
      print("Found Nothing") 
     } 
    } 

的API:http://www.wsvh.nl/wp-json/wp/v2/posts

我的目標是簡單地調用,並打印出的東西,如標題(這是BTW還嵌套更?)。我試圖讓它與slug一起工作,因爲我不像所呈現的標題那樣嵌套,所以我想我應該從最簡單的部分開始,但我甚至無法設法讓它工作。

在此先感謝。

回答

1

該API返回一個陣列字典,其中每個字典表示[String: Any]類型的郵政

Alamofire.request(_newsURL).responseJSON { response in 
    if let posts = response.result.value as? [[String: Any]] { 
    posts.forEach { post in 
     if let slug = post["slug"] as? String { 
     print("Slug: \(slug)") 
     } 
     if let title = post["title"] as? [String: String] { 
     print("Title: \(title["rendered"])") 
     } 
     if let categories = post["categories"] as? [Int] { 
     print("Categories: \(categories)") 
     } 
     // You can retrieve as many field as you like as above... 
    } 
    } 
} 

我強烈建議你利用的對象映射庫的諸如ObjectMapper所以你不必擔心類型檢查或鑄造。

只需創建一個名爲Post模型:

import ObjectMapper 

class Post: Mappable, CustomStringConvertible { 

    var title: String? 
    var slug: String? 

    var link: URL? 
    var content: String? 

    required init?(map: Map) {} 

    func mapping(map: Map) { 
    title <- map["title.rendered"] 
    slug <- map["slug"] 

    link <- (map["link"], URLTransform()) 
    content <- map["content.rendered"] 
    } 

    var description: String { 
    return "Post <\(title ?? "No title")>" 
    } 
} 

,所以你可以檢索的所有帖子如下:

import AlamofireObjectMapper 

Alamofire.request("http://www.wsvh.nl/wp-json/wp/v2/posts") 
    .responseArray { (response: DataResponse<[Post]>) in 

    // This will give you the array of Post objects. 
    print("Posts: \(response.result.value)") 
} 

我爲您創建了一個example project。您可以下載並使用它來更好地瞭解如何執行映射。

+0

最後,打印出的請求!但是,我的最終目標是將其製作爲tableview,因此我需要使Title成爲一個var,以便我可以使用它來操作文本。但試圖使標題變成一個變種給我和錯誤,因爲它不是一個字符串。 – Flowne

+0

神聖莫里!非常感謝你:D這完全解決了我所有的問題,爲你節省了我最大的頭痛。 – Flowne

1

對於這種類型的任務,我建議你使用SwiftyJSON。它會幫助你保持簡單和乾淨的事情。 例如

Alamofire.request(_newsURL).responseJSON(completionHandler: { 
     response in 
     if let value = response.result.value { 
      let json = JSON(value) //Don't forget to import SwiftyJSON 
      debugPrint(json) 
      debugPrint(json[0]["slug"].stringValue) //print value of slug property 
      debugPrint(json[0]["title"]["rendered"].stringValue) //print nested value of title 
     } 
    }) 
+0

哦,哇,這真的很好!我只是想知道,爲了使標題變爲var,我需要做些什麼,所以我可以使用它來操縱TableView? – Flowne