How to pair a string to jsonObject Xcode (Swift)

0
let request = NSMutableURLRequest(url: NSURL(string: "https://blablabla.php")! as URL)
    request.httpMethod = "POST"
    request.httpBody = "Accion=SincronizarProducto".data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest)
    {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }
        else
        {
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            let jsonString = responseString?.substring(from: 1)
            print(jsonString)
        }
    }
    task.resume()
}

I need to pass the jsonString variable to jsonObjects.

This I receive from the json and I need to get the values of NAME, STOCK AND VALUE.

[{"CODIGO":"     9013","NOMBRE":"PIERNA NOVILLO CATEG. V","CENTRO":"2400","CODIGO_R":" ","UNIDAD":"PZ","NOMBRE_C":"AASA CAMER","MARCA_ST":"S","CONVERSION":80,"DESCUENTO":0,"STOCK":83,"VALOR":2820},{"CODIGO":"     9014","NOMBRE":"PALETA NOVILLO CATEG. V","CENTRO":"2400","CODIGO_R":" ","UNIDAD":"PZ","NOMBRE_C":"AASA CAMER","MARCA_ST":"S","CONVERSION":80,"DESCUENTO":0,"STOCK":84,"VALOR":2820},{"CODIGO":"     9019","NOMBRE":"PIERNA VACA CATEG. V","CENTRO":"2400","CODIGO_R":" ","UNIDAD":"PZ","NOMBRE_C":"AASA CAMER","MARCA_ST":"S","CONVERSION":70,"DESCUENTO":0,"STOCK":2,"VALOR":2100}]

Thank you.

    
asked by Juan Sepulveda 29.04.2018 в 21:35
source

1 answer

0

Once you have your data you can do something like this, you have to clean the code:

if let data = data {
    let objects = try? JSONSerialization.jsonObject(with: data, options: [])

    if let objects = objects as? [[String: Any]]{
        for object in objects {
            print(object["NOMBRE"] as? String ?? "Sin Info")
            print(object["STOCK"] as? Int ?? 0)
            print(object["VALOR"] as? Int ?? 0)
        }
    }
}
    
answered by 08.06.2018 в 23:26