2017-09-04 51 views
-1

因此,我收到一些服务器的JSON数据,现在我试图将它保存为一个数组,所以我可以用它填充一个tableview,但在这里遇到麻烦是我的代码:如何将解析的json数据保存到一个数组与swift 3

class UserInfo : UIViewController{ 
var main = "" 
session.dataTask(with: url) { (data, response, error) in 
     if let response = response { 
      print (response) 
     } 
     if let data = data { 
      let json = (try? JSONSerialization.jsonObject(with: data, options: [])) 
      print(json) 
      guard let array = json as? [Any] else {return} 
      for info in array { 
      guard let infoDict = info as? [String : Any] else{return} 
      //there is a declared var called main 
      //main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error 
      self.main = infoDict["Title"] as! String 
      print (self.main) 
} 
} 
}.resume() 
} 
+0

因此,您需要发布收到的json,以便我们知道我们处理的是什么数据。 – ovidiur

+0

“但我得到错误”什么错误? – Larme

+0

你想将这些数据存储在UserDefaults中? – shahnilay86

回答

1

首先你必须声明ary以外的请求范围。然后,您必须将数据存储在相同的ary中。

var ary: NSMutableArray = NSMutableArray() 

session.dataTask(with: url) { (data, response, error) in 
      if let response = response { 
       print (response) 
      } 
      if let data = data { 
       let json = (try? JSONSerialization.jsonObject(with: data, options: [])) 
       print(json) 
       guard let array = json as? [Any] else {return} 
       for info in array { 
        guard let infoDict = info as? [String : Any] else{return} 
        //there is a declared var called main 
        //main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error 
        self.main = infoDict["Title"] as! String 
        self.ary.add(self.main) 
        print (self.main) 
       } 
       print("Final array is :::",self.ary) 
      } 
      }.resume() 

试试上面的代码。希望它能为你工作。

+0

工作正常,但我只是添加了“自我”这个“打印(”最终阵列是:::“,self.ary)” –

+0

@ Duck.P是的,对不起,因为我们要求从服务器获取数据,这是一个封闭的问题,谢谢 – shahnilay86

+0

FUNC的tableView(_的tableView:UITableView的,cellForRowAt indexPath:IndexPath) - >的UITableViewCell { 让细胞=的UITableViewCell?(样式:UITableViewCellStyle.default,reuseIdentifier: “小区”) cell.textLabel的.text = ARRY //当我这样做(cell.textlable?.text = arry)我得到错误(无法分配//类型'NSMutableArray'的值来键入'String?') return(cell) } –

相关问题