[英]How to parse an Jsonobject to string (swift)
My program receives the following JSON array from an API我的程序从 API 接收以下 JSON 数组
[{
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.我想将所有这些放入一个数组中,以便我使用它来填充 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.您提供的 String 表面上看起来像 JSON,但它不符合规范,因此如果这确实是您从 API 获得的内容,那么您将很难找到接受它的 JSON 解析器。 In light of the
Codable
protocol I defined根据我定义的
Codable
协议
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:这允许我编码和打印一个有效的 JSON 对象,如下所示:
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.这演示了您的 JSON 字符串应该如何真正构建。 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.这仍然是一个快速而肮脏的例子,因为有更好的方法可以将大写的 JSON 键转换为小写的 Swift 样式属性,但这只会使问题变得混乱。 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.
恐怕你必须把你的 JSON 弄明白,否则(优秀的)Swift JSON 支持对你没有多大帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.