简体   繁体   中英

How to parse an Jsonobject to string (swift)

My program receives the following JSON array from an API

[{
   Direccion = "";
   Imagen = hospital;
   Nombre = "Centro Antirr\U00e1bico Municipal(S.S.A.)";
   Telefono = "(52)(222) 220 15 94";
}, {
   Direccion = "";
   Imagen = hospital;
   Nombre = "Rescate y Primeros Auxilios de Puebla ";
   Telefono = "";
}, {
   Direccion = "";
   Imagen = policia;
   Nombre = "Denuncia ciudadana an\U00f3nima";
   Telefono = 089;
}]

I want to put all that into an array in order for me to use it to fill a tableview. I've try to parse it to string but I a get this error

"Could not cast value of type '__NSDictionaryM' (0x10693f418) to 'NSString'"

Heres my code:

@IBOutlet weak var labelAPI: UILabel!


let sections = ["Directorio"]
var arreAPI: [String] = []

    do {
            let todo = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.mutableContainers) as! [Any]
            //let todo = try JSONSerialization.jsonObject(with: responseData) as! [[String: Any]]

            DispatchQueue.main.async { // Correct
                self.arreAPI=todo as! [String]
                self.labelAPI?.text = todo[5] as? String
            }
    } catch  {
            print("Error al convertir data a JSON")
            //return
        }
    }
    task.resume()
}

Can anybody help?

The String you provide superficially looks like JSON, but it does not conform to the spec , so if that is really what you get from your API then you will be in trouble to find a JSON-parser accepting it. In light of the Codable protocol I defined

struct Directorio :Codable {
    let Direccion : String
    let Imagen : String
    let Nombre : String
    let Telefono : String
}

which allowed me to encode and print a valid JSON-object as follows:

let encoder = JSONEncoder()
let dir = Directorio(Direccion: "", Imagen: "hospital",
                     Nombre: "Centro Antirr\u{00e1}bico Municipal(S.S.A.)", 
                     Telefono: "(52)(222) 220 15 94")
let dirData = try! encoder.encode(dir)
print(String(data: dirData, encoding: .utf8)!)

this will print

{"Nombre":"Centro Antirrábico Municipal(S.S.A.)","Direccion":"","Telefono":"(52)(222) 220 15 94","Imagen":"hospital"}

which demonstrates how your JSON-string should really be structured. Making the necessary corrections you can parse it as follows:

let res = """
[{
    "Direccion" : "",
    "Imagen" : "hospital",
    "Nombre" : "Centro Antirr\u{00e1}bico Municipal(S.S.A.)",
    "Telefono" : "(52)(222) 220 15 94"
}, {
    "Direccion" : "",
    "Imagen" : "hospital",
    "Nombre" : "Rescate y Primeros Auxilios de Puebla ",
    "Telefono" : ""
}, {
    "Direccion" : "",
    "Imagen" : "policia",
    "Nombre" : "Denuncia ciudadana an\u{00f3}nima",
    "Telefono" : "089",
}]
"""

let jsonData = res.data(using: .utf8)!
let decodr = JSONDecoder()

do {
    let todo = try decodr.decode([Directorio].self, from: jsonData)
    print(todo[2].Telefono)
} catch {
    print("error on decode: \(error.localizedDescription)")
}

This is still a quick and dirty example, since there are better ways to convert your upper case JSON-keys to lower case Swift-style properties, but that would just clutter the issue. I am afraid you will have to get your JSON straight, otherwise the (excellent) Swift JSON-support won't be of much help to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM