Reputation: 5107
I am working on trying to serialize a JSON string. This one:
"user": {
apellidos = "Vasco Fornas";
"created_at" = "<null>";
email = "[email protected]";
"id_usuario" = 122;
imagen = "1ufm2Fmifoto.jpeg";
name = "";
"nivel_usuario" = 1;
nombre = Modesto;
unidad = 0;
"updated_at" = "<null>";
}, "uid": , "error": 0]
{
apellidos = "Vasco Fornas";
"created_at" = "<null>";
email = "[email protected]";
"id_usuario" = 122;
imagen = "1ufm2Fmifoto.jpeg";
name = "";
"nivel_usuario" = 1;
nombre = Modesto;
unidad = 0;
"updated_at" = "<null>";
}
And this is my code so far:
do {//creamos nuestro objeto json
print("recibimos respuesta")
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
//Do with json
print(json);
DispatchQueue.main.async {//proceso principal
let mensaje = json["user"]
print(mensaje!);
}
}
}
The first print shows the complete JSON string, and the second print shows the item "user"
How could I get the values for all keys under "user" item?
Upvotes: 1
Views: 214
Reputation: 10105
you can try this, eg:
if let mensaje = json["user"] as? [String:String] {
for key in mensaje.keys {
let currentValue = mensaje[key] as? String ?? "" // cast whatever you like
print(currentValue)
}
}
or getting values as array...
if let mensaje = json["user"] as? [String:String] {
let yourValues = Array(mensaje.values)
print(yourValues)
}
if you are searching for "apellidos":
var apellidos?
if let mensaje = (json["user"] as? [String:String]) {
apellidos = mensaje["apellidos"] as? String ?? ""
}
print(apellidos)
Upvotes: 2