好的,为了澄清,我如何引用cedula:string,codzona:string,dectionamento:string作为此词典中的属性:
["exito": 1, "data": {
lugarVotacion = {
cedula = 75095734;
codZona = 90;
departamento = CALDAS;
direccion = "CL 65 #26-10";
fecing = "1999-05-24 00:00:00.0";
mesa = 19;
municipio = MANIZALES;
puesto = "UNIVERSIDAD DE CALDAS";
};
}
]
我已将jsonserialization应用于服务器响应,结果得到了此数组:
func parseJSON(data: Data) -> [String: Any]? {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print("Errror: (error.localizedDescription)")
return nil
}
}
结果:
["exito": 1, "data": {
lugarVotacion = {
cedula = 75095734;
codZona = 90;
departamento = CALDAS;
direccion = "CL 65 #26-10";
fecing = "1999-05-24 00:00:00.0";
mesa = 19;
municipio = MANIZALES;
puesto = "UNIVERSIDAD DE CALDAS";
};
}
]
下一步是如何解析Cedula,Codzona,Dewartamento,dirección,Fecing,Mesa,Municipio,Puesto,Puesto作为字符串变量?
好。我已经弄清楚了。感谢@rmaddy指出的。响应是迅速的词典。我以这种方式访问了元素:
guard let datos = lugarVotacion["lugarVotacion"] as? [String: Any] else {
return
}
let puesto = datos["puesto"]
print(puesto)
您可以使用SWIFT中的字典语法直接访问元素,也可以使用Encodable and Decodable
协议。
您只需要创建以下Struct
:
struct LugarVotacion: Decodable {
let cedula: Int
let codZona: Int
let departamento: String \ I am not sure which kind of class you had used here
let direccion: String
let fecing: String
let mesa: Int
let municipio: String \ I am not sure which kind of class you had used here
let puesto: String
}
并将此代码添加到解码:
let lugarVotacion = try JSONDecoder().decode(LugarVotacion.self, from: json) // Decoding our data
print(lugarVotacion) // decoded!!!!!