如何在swift 4中解析下一个混合数组

时间:2018-02-11 17:54:05

标签: arrays json swift

好的,为了澄清,我怎样才能引用cedula:String,codZona:String,departamento:String as this dictionary in this dictionary:

["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,departamento,dirección,fecing,mesa,municipio,puesto作为String变量?

2 个答案:

答案 0 :(得分:0)

确定。我已经弄清楚了。感谢@rmaddy指出。响应是一个快速的字典。我以这种方式访问​​了元素:

guard let datos = lugarVotacion["lugarVotacion"] as? [String: Any] else {
        return
    }
    let puesto = datos["puesto"]
    print(puesto)

答案 1 :(得分:-1)

您可以使用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!!!!!