2017-02-09 34 views
0

我已經從Alamofire和SwiftyJSON一個JSON結果,我試圖創建字典從它創建一個數組夫特3 JSON陣列到字典

JSON結果

JSON: [ 
    { 
    "p_589b6a49a0bfd" : { 
     "path" : "\/uploads\/588fa43eba3c9\/588fa43eba3c9_1486580297.jpg", 
     "likes" : "0", 
     "userid" : "588fa43eba3c9", 
     "caption" : "Bae", 
     "comments" : "0", 
     "date" : "1486580297" 
    } 
    }, 
    { 
    "p_589b7f1c540f1" : { 
     "path" : "\/uploads\/588fa43eba3c9\/588fa43eba3c9_1486585628.jpg", 
     "likes" : "0", 
     "userid" : "588fa43eba3c9", 
     "caption" : "Hot stuff bitch ", 
     "comments" : "0", 
     "date" : "1486585628" 
    } 
    } 
] 

請求/響應

Alamofire.request(BASE_URL + "index.php/feed/build", method: .get, headers: headers).responseJSON { response in 

     switch response.result { 

     case .success(let value): 
      let json = JSON(value) 
      print("JSON: \(json)") 

     case .failure(let error): 
      print(error) 

     } 

    } 

然後我建立了一個名爲'FeedPost'的簡單類,它將存儲JSON響應中的每個元素(這是FeedPost類中的函數)

init(postid: String, postData: Dictionary<String, AnyObject>) { 

    self._postid = postid 

    if let caption = postData["caption"] as? String { 
     self._caption = caption 
    } 

    if let path = postData["path"] as? String { 
     self._path = path 
    } 

    if let likes = postData["likes"] as? Int { 
     self._likes = likes 
    } 

    if let comments = postData["comments"] as? Int { 
     self._comments = comments 
    } 

    if let userid = postData["userid"] as? String { 
     self._userid = userid 
    } 

    if let date = postData["date"] as? String { 
     self._date = date 
    } 

} 

我需要通過JSON循環創建一個字典傳遞給FeedPost,然後在請求期間將每個FeedPost添加到另一個名爲Posts的數組。以'p_'開頭的字符串我想用作郵政編碼

回答

3

使用Alamofire響應,您使用了SwiftyJSON,並且您的FeedPost init使用了swift本地字典。所以我建議你使用SwiftyJSON或swift的本地類型。既然你已經添加了init字典,我正在用原生類型回答你的答案。

Alamofire.request(BASE_URL + "index.php/feed/build", method: .get, headers: headers).responseJSON { response in 

    switch response.result { 

    case .success(let value): 
     If let dic = value as? [String: Any], 
      let array = DIC["JSON"] as? [[String: Any]] { 
       for item in array { 
        for (key, value) in item { 
          If let subDic = value as? [String: Any] { 
           let obj = FeedPost(postid: key, postData: subDic) 
          } 
        } 
       } 
     } 
     print("JSON: \(json)") 

    case .failure(let error): 
     print(error) 

    } 

} 

注:正確的字典中迅速3 JSON對象是[String: Any][String: AnyObject]所以你的初始化參數POSTDATA的類型更改爲[String: Any]

+0

obj的我把它添加到一個變量 'VAR帖子後= [FeedPost]()'' self.posts.append(OBJ)' 但是當我嘗試將其打印出來,它只是打印[ FeedPost,FeedPost] – Chad

+0

@Chad您正在打印'FeedPost'自定義對象的數組,以便它向您顯示對象類型,它沒有任何問題。現在你只需要tableView來顯示這個數組的信息。 –

+0

完美,謝謝! – Chad

1

以下是可用於您的情況的代碼,此代碼從遊樂場複製而來。

import UIKit 

typealias JSONDictionary = [String: AnyObject] 

    class Post { 
     let id: String 
     let userId: String? 
     let date: Double? 
     let caption: String? 
     let comments: Double? 
     let likes: Double? 
     let path: String? 

     init?(with dictionary: JSONDictionary) { 
      guard let postId = dictionary.keys.first, let postInfo = dictionary[postId] as? JSONDictionary else { return nil } 

      self.id = postId 
      self.userId = postInfo["userid"] as? String 
      self.date = postInfo["date"] as? Double 
      self.caption = postInfo["caption"] as? String 
      self.comments = postInfo["comments"] as? Double 
      self.likes = postInfo["likes"] as? Double 
      self.path = postInfo["path"] as? String 
     } 
    } 

解析JSON數組就像這樣。

case .success(let value): 
    let jsonArray = value["JSON"] as? [JSONDictionary] 
    let posts = jsonArray?.flatMap(Post.init(with:)) 
    print("Posts \(posts)" 
case .failure: break 

我一直在使用一個本地JSON文件中的一個操場&代碼是這樣的嘗試這一點。

let url = Bundle.main.url(forResource: "data", withExtension: "json") 
let data = try! Data(contentsOf: url!) 

let jsonArray = try! JSONSerialization.jsonObject(with: data , options: .allowFragments) as? [JSONDictionary] 
let posts = jsonArray?.flatMap(Post.init(with:)) 
+0

通過此代碼,我得到'對成員jsonObject的模糊引用(with:options :) 'let jsonArray = try! JSONSerialization.jsonObject(with:value,options:.allowFragments)as? [JSONDictionary] let posts = jsonArray.flatMap(Post.init(with:JSONDictionary)) print(「Posts \(posts)」) – Chad

+0

我覺得你不需要這段代碼,你會得到解析的json對象即價值。我提到過這種情況,如果你要試試這個。 –

+0

啊我看到現在使用這個 'let jsonArray = value [「JSON」] as? [JSONDictionary] let posts = jsonArray?.flatMap(Post.init(with :))' 我得到類型'any'沒有下標成員,'value'被突出顯示爲錯誤? – Chad