[英]How to parse an Jsonobject to string (swift)
我的程序从 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;
}]
我想将所有这些放入一个数组中,以便我使用它来填充 tableview。 我尝试将其解析为字符串,但出现此错误
"Could not cast value of type '__NSDictionaryM' (0x10693f418) to 'NSString'"
这是我的代码:
@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()
}
有人可以帮忙吗?
您提供的 String 表面上看起来像 JSON,但它不符合规范,因此如果这确实是您从 API 获得的内容,那么您将很难找到接受它的 JSON 解析器。 根据我定义的Codable
协议
struct Directorio :Codable {
let Direccion : String
let Imagen : String
let Nombre : String
let Telefono : String
}
这允许我编码和打印一个有效的 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)!)
这将打印
{"Nombre":"Centro Antirrábico Municipal(S.S.A.)","Direccion":"","Telefono":"(52)(222) 220 15 94","Imagen":"hospital"}
这演示了您的 JSON 字符串应该如何真正构建。 进行必要的更正,您可以按如下方式解析它:
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)")
}
这仍然是一个快速而肮脏的例子,因为有更好的方法可以将大写的 JSON 键转换为小写的 Swift 样式属性,但这只会使问题变得混乱。 恐怕你必须把你的 JSON 弄明白,否则(优秀的)Swift JSON 支持对你没有多大帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.