2017-02-09 76 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