在Swift 3中解析JSON文件时出错

时间:2018-07-11 16:26:22

标签: json swift

我是Swift的新手,使用Swift 3代码解析JSON时遇到了一些问题。

这是我的JSON(摘录):

[  
   {  
      "COD_USUARIO":"4",
      "0":"4",
      "USUARIO":"PIEDAD",
      "1":"PIEDAD",
      "CLAVE":"MU\u00d1OZ",
      "2":"MU\u00d1OZ",
      "ACTIVO":"1",
      "3":"1",
      "FECHA_ALTA":"2010-12-07 00:00:00",
      "4":"2010-12-07 00:00:00",
      "FECHA_BAJA":null,
      "5":null,
      "CIF":null,
      "6":null,
      "TELEFONO_CASA":"",
      "7":"",
      "TELEFONO_MOVIL":"",
      "8":"",
      "EMAIL_TRABAJO":"",
      "9":"",
      "EMAIL_PARTICULAR":"",
      "10":"",
      "COLOR":"16777215",
      "11":"16777215",
      "ADMINISTRADOR":"0",
      "12":"0",
      "COD_PERSONA":"9",
      "13":"9",
      "IMPRESORA_ETIQUETAS":"",
      "14":"",
      "IMP_JUSTIFICANTES":"",
      "15":"",
      "VER_SESIONES":"0",
      "16":"0",
      "COD_EMPRESA":"0",
      "17":"0",
      "FECHA_TRABAJO":null,
      "18":null,
      "MEMORIZAR_FECHA":"0",
      "19":"0",
      "AVISOS_PAGOS":"0",
      "20":"0",
      "AVISOS_COBROS":"0",
      "21":"0",
      "AVISOS_DIAS":"0",
      "22":"0",
      "AVISOS_CONTRATOSC":"0",
      "23":"0",
      "24":"0"
   }
]

这是我的代码(摘录):

let url = URL(string : "http://192.168.0.252:6996/datos/policlinica/webservices/valida.php")
let session = URLSession.shared

let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"

let paramToSend = "usu=" + user + "&pass=" + pwd

request.httpBody = paramToSend.data(using: String.Encoding.utf8)

let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
    guard let _:Data = data else{
        return
    }

    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: [])
        print (json) //I can see my json in console

        let cod_persona = json["COD_USUARIO"]
        print (cod_persona)
        //error: Type 'Any' has no subscript members
    } catch {
        print ("error")
        return
    }
})
task.resume()

我尝试了许多Internet实例,但是无法读取特定的JSON数据。例如,我想读取“ COD_USUARIO”字段并将数据保存在变量中,但是我无法使其正常工作。

关于这个主题的任何建议或我在做什么错(确定很多事情)

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您的json包含数组对象,所以我这样称呼它:

json[0]["COD_USUARIO"]

因为COD_USUARIO位于json的第一个数组中。