arrays - 从 JSON 解析数组内的字典获取数据

标签 arrays json swift dictionary

我有一个充满字典的数组,

(
    {
    "id_color" = 8;
    nombre = "Amarillo p\U00e1lido";
},
    {
    "id_color" = 9;
    nombre = "Amarillo p\U00e1lido/toffy claro";
},
    {
    "id_color" = 13;
    nombre = Azul;
},
    {
    "id_color" = 12;
    nombre = Magenta;
},
    {
    "id_color" = 18;
    nombre = Morado;
})

我可以访问字典的数据来执行此操作:

let coloresArray = jsonResult["colores"] as! NSArray
            let colorDict = coloresArray[0] as! NSDictionary
            print (colorDict["nombre"]!)

但是有没有办法访问键的值做这样的事情

jsonResult["colores"][0]["nombre"]

感谢您的回答

最佳答案

您需要正确地施放步骤。解析 JSON 数据时避免强制转换和强制展开。

获取所需数据的正确且安全的方法是:

if let colores = jsonResult["colores"] as? [[String:Any]], let nombre = colores[0]["nombre"] as? String {
    print(nombre)
}

关于arrays - 从 JSON 解析数组内的字典获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49240549/

相关文章:

json - RxSwift 可观察到的错误停止链 - 使用 Rx 的 Web 服务,如何恢复?

Swift4:强制转换从 'Data?' 到 'Data' 只解包选项;你是想使用 '!' 吗?

c++ - 如何防止删除成员函数返回的指针?

PHP 引用参数与返回函数

javascript - 在Js中如何操作数组但也要考虑数组可能只是一个元素

C 错误 "subscripted value is neither array nor pointer"

javascript - 如何从数组中的JSON对象获取属性值,并写入url

java - Angular 不使用 [UTC] 转换 json 日期

swift - URLSession : use http/1. 1 而不是 http/2

使用 Firebase 的 iOS 推送通知