2016-09-15 89 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