2016-09-15 83 views
0

我一直在使用快速的应用程序。 IM停留在分析多个数据作为一个数组,这里是我的JSONSwift解析JSON作为数组

{ 
"error":0, 
"success":1, 
"kode_keranjang":"2", 
"kode_produk":"1", 
"kode_pelanggan":"USR-6cs42", 
"jumlah":"1", 
"nama_produk":"MacBook 2015", 
"gambar":"MacBook.jpg", 
"harga":"2000000", 
"message":"Berhasil" 
} 
{ 
"error":0, 
"success":1, 
"kode_keranjang":"3", 
"kode_produk":"2", 
"kode_pelanggan":"USR-6cs42", 
"jumlah":"1", 
"nama_produk":"iPhone 6s", 
"gambar":"iPhone", 
"harga":"12000000", 
"message":"Berhasil" 
} 

我怎样才能nama_produk作为SWIFT一个数组?所以我可以在我的tableview细胞填充它

,这里是我的SWIFT

 let myUrl = NSURL(string: "http://xxxxxxxx.com/produk.php"); 

    let request = NSMutableURLRequest(URL:myUrl!); 

    request.HTTPMethod = "POST";// Compose a query string 

    let postString = "produkid="+produkid!+"&kat="+kat!+""; 

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); 

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { 
     data, response, error in 

     if error != nil 
     { 
      print("error=\(error)") 
      return 
     } 

     // You can print out response object 
     print("response = \(response)") 

     // Print out response body 
     let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) 
     print("responseString = \(responseString)") 

     //Let's convert response sent from a server side script to a NSDictionary object: 
     do { 
      let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary 

      if let parseJSON = myJSON { 

       // Now we can access value of First Name by its key 
       let nama_produk = parseJSON["nama_produk"] as? NSArray 
       let status = parseJSON["success"] as? Int 
       if(status == 1){ 


        print (nama_produk); 
       } 
       else{ 
        // let statusnya = "error"; 
        return; 
       } 

      } 
     } catch { 
      print(error) 
     } 
    } 
    task.resume() 

在这一行

let nama_produk = parseJSON["nama_produk"] as? NSArray 


print (nama_produk); 

我创建nama_produk为数组,然后我尝试打印,但空不显示数据。

然后我想在我的小区添加nama_produk阵列这样

var nama_produk_array = [""+nama_produk+""] 
cell.namaproduk.text = nama_produk_array[indexPath.row] 

如何可以解析JSON到数组?

请人

+1

这JSON不是数组。 – Alexander

+0

我可以只使用该JSON或我必须更改JSON? – themasmul

+1

你有什么是无效的JSON。 JSON必须具有单个根级别对象,可以是数组或字典。你有什么是多个字典。也许你打算把所有这些字典都放在一个根级数组中? – Alexander

回答

2

至于我能理解你有字典的数组,并要提取nama_produk场入阵。这里是安全的方式来做到这一点在夫特3时,Xcode 8

var jsonString1 = 
"{\"error\":0,\"success\":1,\"kode_keranjang\":\"2\",\"kode_produk\":\"1\",\"kode_pelanggan\":\"USR-6cs42\",\"jumlah\":\"1\",\"nama_produk\":\"MacBook 2015\",\"gambar\":\"MacBook.jpg\",\"harga\":\"2000000\",\"message\":\"Berhasil\"}" 
var jsonString2 = 
"{\"error\":0,\"success\":1,\"kode_keranjang\":\"3\",\"kode_produk\":\"2\",\"kode_pelanggan\":\"USR-6cs42\",\"jumlah\":\"1\",\"nama_produk\":\"iPhone 6s\",\"gambar\":\"iPhone\",\"harga\":\"12000000\",\"message\":\"Berhasil\"}" 
var jsonString = "[" + jsonString1 + "," + jsonString2 + "]" 

var data = jsonString.data(using: .utf8)! 
do { 
    if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] 
    { 
     let array = json 
      .filter{ $0["success"] as? Int == 1} 
      .flatMap{$0["nama_produk"] as? String} 
     print(array) // ==> ["MacBook 2015", "iPhone 6s"] 
    } else { 
     print("bad json") 
    } 
} catch let error as NSError { 
    print(error) 
} 

jsonString能够JSON =>所述的2个字典jsonString1jsonString2

flatMap需要的失败铸件护理阵列$0["nama_produk"]String,可能不必要隐藏你收到JSON的问题,所以你可能会考虑使用为Alexander建议

+2

您可以使用地图来做 – Alexander

+0

你对地图有什么意义?就像用map关闭替换json for-loop一样?或者让'Decodable'结构将json值映射到相应的属性? –

+0

看看我的答案。 – Alexander

2

什么您提供的是无效的JSON。你必须有一个单独的顶层元素。也许你打算把它放在一个阵列,像这样:

[ 
    { 
     "error": 0, 
     "success": 1, 
     "kode_keranjang": "2", 
     "kode_produk": "1", 
     "kode_pelanggan": "USR-6cs42", 
     "jumlah": "1", 
     "nama_produk": "MacBook 2015", 
     "gambar": "MacBook.jpg", 
     "harga": "2000000", 
     "message": "Berhasil" 
    } { 
     "error": 0, 
     "success": 1, 
     "kode_keranjang": "3", 
     "kode_produk": "2", 
     "kode_pelanggan": "USR-6cs42", 
     "jumlah": "1", 
     "nama_produk": "iPhone 6s", 
     "gambar": "iPhone", 
     "harga": "12000000", 
     "message": "Berhasil" 
    } 
] 

这是我在serg_zhdanswer改进:

import Foundation 

var jsonFragment1 = 
"{\"error\":0,\"success\":1,\"kode_keranjang\":\"2\",\"kode_produk\":\"1\",\"kode_pelanggan\":\"USR-6cs42\",\"jumlah\":\"1\",\"nama_produk\":\"MacBook 2015\",\"gambar\":\"MacBook.jpg\",\"harga\":\"2000000\",\"message\":\"Berhasil\"}" 
var jsonFragment2 = 
"{\"error\":0,\"success\":1,\"kode_keranjang\":\"3\",\"kode_produk\":\"2\",\"kode_pelanggan\":\"USR-6cs42\",\"jumlah\":\"1\",\"nama_produk\":\"iPhone 6s\",\"gambar\":\"iPhone\",\"harga\":\"12000000\",\"message\":\"Berhasil\"}" 
var jsonString = "[" + jsonFragment1 + "," + jsonFragment2 + "]" 


func parse(JSON json: String) throws -> [String]? { 
    guard let data = json.data(using: .utf8) else { return nil } 

    guard let rootArray = try JSONSerialization.jsonObject(with: data, options : []) as? [[String: Any]] 
    else { return nil } 

    return rootArray 
     .filter{ $0["success"] as? Int == 1} 
     .map{ $0["nama_produk"] as! String } 
} 

if let devices = try parse(JSON: jsonString) { 
    print(devices) 
} 
else { 
    print("error parsing the json") 
} 

你可以try it here

+0

在上面的编码中,你的JSON数组也是无效的格式 –

+0

@MohanSingh你能否详细说明一下? – Alexander

+0

在代码上方的JSON数组上看到它。两个词典,这使得Json无效 –

2

我得到你需要将JSON对象应用到你的表视图。我认为只有你需要将几个对象转换为一个数组。这是我简单明了的解决方案。

有效JSON:

所提供的JSON是无效的。所以我主持了valid format

例如:[array {字典},{字典}]

注意:不要忘了在info.plist添加App Transport Security Settings加载的HTTP URL

创造一个自定义类

//FileName : JSONTableData.swift 

import UIKit 

class JSONTableData 
{ 
    var tempString:String 

    init(tempString:String) 
    { 
     self.tempString = tempString 
    } 
} 

在视图控制器

import UIKit 

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { 

    @IBOutlet weak var tableView: UITableView! 

    var tableData = Array<JSONTableData>() 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     getFromJSON() 

    } 


    //Get from JSON 
    // In swift 2.0, swift 2.2 
    // For swift 3.0 is below 
    func getFromJSON() 
    { 
     let URL = NSURL(string: "http://getmydetails.pe.hu/test/jsontableview.php") 
     let request = NSMutableURLRequest(URL: URL!) 
     let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in 
      guard error == nil && data != nil else 
      { 
       print("Error:", error) 
       return 
      } 
      let httpStatus = response as? NSHTTPURLResponse 
      if httpStatus!.statusCode == 200 
      { 
       if data?.length != 0 
       { 
        let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) //as? [AnyObject] 
        let namma = received as? [AnyObject] 

        for porduk in namma! 
        { 
         print(porduk) 

         let nammaporduk = porduk["nama_produk"] as! String 

         dispatch_async(dispatch_get_main_queue()) 
         { 
          self.tableData.append(JSONTableData(tempString: nammaporduk)) 
          self.tableView.reloadData() 
         } 
        } 

       } 
       else 
       { 
        print("No Data got from URL") 
       } 
      } 
      else 
      { 
       print("HTTP Status error is: ",httpStatus!.statusCode) 
      } 
     } 
     task.resume() 
    } 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

     return 1 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     return tableData.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell 

     let tableObject:JSONTableData = tableData[indexPath.row] 
     cell.cellLabel.text = tableObject.tempString 
     return cell 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
     } 
    } 

在迅速3.0

import UIKit 

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { 

    @IBOutlet weak var tableView: UITableView! 

    var tableData = Array<JSONTableData>() 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     getFromJSON() 

    } 


    //Get from JSON 

    func getFromJSON() 
    { 
     let URL = NSURL(string: "http://getmydetails.pe.hu/test/jsontableview.php") 
     let request = NSMutableURLRequest(url: URL! as URL) 
     let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in 
      guard error == nil && data != nil else 
      { 
       print("Error:", error) 
       return 
      } 
      let httpStatus = response as? HTTPURLResponse 
      if httpStatus!.statusCode == 200 
      { 
       if data?.count != 0 
       { 
        let received = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) //as? [AnyObject] 
        let namma = received as? [AnyObject] 

        for porduk in namma! 
        { 
         print(porduk) 

         let nammaporduk = porduk["nama_produk"] as! String 
         DispatchQueue.main.sync 
         { 
          self.tableData.append(JSONTableData(tempString: nammaporduk)) 
          self.tableView.reloadData() 
         } 
        } 

       } 
       else 
       { 
        print("No Data got from URL") 
       } 
      } 
      else 
      { 
       print("HTTP Status is 200. But error is: ",httpStatus!.statusCode) 
      } 
     } 
     task.resume() 
    } 

    private func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     return tableData.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! TableViewCell 

     let tableObject:JSONTableData = tableData[indexPath.row] 
     cell.cellLabel.text = tableObject.tempString 
     return cell 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

输出: enter image description here