Swift Parse JSON As Array

时间:2016-09-15 19:39:13

标签: ios json swift

我一直在使用swift app。我坚持将多个数据解析为数组,这里是我的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"
}

如何在swift中将nama_produk作为数组?所以我可以在我的tableview单元格中填充它

这里是我的快速

        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解析为数组?

请某人

3 个答案:

答案 0 :(得分:2)

据我所知,你有一系列字典,并希望将nama_produk字段提取到数组中。这是在 Swift 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 =&gt; 2个词典jsonString1jsonString2

的数组

flatMap会处理$0["nama_produk"]String的失败演员,这可能不必要隐藏您收到的json问题,因此您可以考虑将.map{ $0["nama_produk"] as! String }用作{ {3}}建议

答案 1 :(得分: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_zhd answer {/ 3>}的改进:

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

答案 2 :(得分:0)

struct Product: Decodable {
    let namaProduk: String?
}

let JSON: String = """
[{
    "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"
}]
"""

if let jsonData = JSON.data(using: .utf8) {

    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase

    do {
        let products: [Product] = try decoder.decode([Product].self, from: jsonData)
        let namaProduks: [String] = products.compactMap { $0.namaProduk }
        print(namaProduks) // ["MacBook 2015", "iPhone 6s"]
    } catch {
        print(error) // handle the error
    }
}