Swift - 如何读取使用json_encode生成的二维数组?

时间:2017-09-20 16:05:08

标签: php ios arrays swift

这是我的php:

$query->bind_param("s", $consulta);
$result = $query->execute();
$query->bind_result($row1, $row2);

if($result)
{   
    $json_response = array();
    while ($query->fetch()) 
    {
        $json_response[] = array("NUMERO" => $row1, "IMAGEN" => $row2);
    }
}
echo json_encode($json_response);

这是我的安排:

[
 {"NUMERO":99512233,”IMAGEN”:”\/imagen.jpg”},
 {“NUMERO":99887766,”IMAGEN”:”\/imagen.jpg”},
 {“NUMERO”:99557744,”IMAGEN”:”\/imagen.jpg”}
]

所以我试着阅读这个安排:

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parse_json = json
{
    print(parse_json[“NUMERO”][0]) //99512233
}

我怎么读这个?

3 个答案:

答案 0 :(得分:0)

您展示的JSON:

[
 {"NUMERO":99512233,”IMAGEN”:”\/imagen.jpg”},
 {“NUMERO":99887766,”IMAGEN”:”\/imagen.jpg”},
 {“NUMERO”:99557744,”IMAGEN”:”\/imagen.jpg”}
]

...在我看来就像一个包含多个词典的数组。

尝试将JSON输出转换为所需类型:

let json = try JSONSerialization.jsonObject(with: data!, 
  options: .mutableContainers)
guard let parse_json = json as? [[String:Any]] else { 
  print("Unable to cast JSON to expected type")
  return
}
print(parse_json[0][“NUMERO”]) //99512233

答案 1 :(得分:0)

首先,您需要将解析后的JSON转换为NSDictionary,然后您可以访问NSDictionary的键和值,如下所示: json.value(forKey: "NUMERO")

答案 2 :(得分:0)

我通过执行以下操作找到了解决方案:

$json_response = array();
if($result)
{   
    while ($query->fetch()) 
    {
        $json_response[] = array("NUMERO"=>(string)$row1,"IMAGEN"=>(string)$row2);
    }
}
echo json_encode($json_response);

在xcode中:

    _ = URLSession.shared.dataTask(with: url_request)
    {(data, response, error) in
                      if(error != nil)
                        {
                            print("Error != nil")
                        }
                        else
                        {
                            if let status_code = response as? HTTPURLResponse
                            {
                                if status_code.statusCode >= 200 && status_code.statusCode < 300
                                {
                                    var json_result = NSArray()
                                    do
                                    {
                                        json_result = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
                                    }
                                    catch
                                    {
                                        print("Error al convertir el arreglo")
                                        print(error.localizedDescription)
                                        return
                                    }

                                    var json_element = NSDictionary()
                                    for x in 0 ..< json_result.count
                                    {
                                        json_element = json_result[x] as! NSDictionary
                                        if let numero = json_element["NUMERO"] as? String,
                                           let imagen = json_element["IMAGEN"] as? String
                                        {
                                            print(numero + " " + imagen)
                                        }
                                        else
                                        {
                                            //No se pudo convertir
                                            print("Nada que mostrar")
                                        }
                                    }
                                }
                                else
                                {
                                    //Error de servidor
                                    print("No se pudo establecer una conexion")
                                }
                            }
                            else
                            {
                                print("No se pudo convertir el URLResponse")
                            }
                        }
 }.resume()