从JSON响应中读取对象并保存在可变数组中

时间:2018-06-05 11:11:58

标签: arrays json swift dictionary

这是我的JSON数据:

let jsonArray = [
    "array": [12.34, 56.78],
    "users": [
        [
            "id": 987654,
            "info": [
                "name": "jack",
                "email": "jack@gmail.com"
            ],
            "feeds": [98, 23443, 213239, 23232]
        ],
        [
            "id": 654321,
            "info": [
                "name": "jeffgukang",
                "email": "jeffgukang@gmail.com"
            ],
            "feeds": [12345, 56789, 12423, 12412]
        ]
    ]
]

我的代码用于阅读"用户"和" id"

let idArr = NSMutableArray()
let infoArr = NSMutableArray()
let usersArr = NSMutableArray()

for index in 0...1 { 
    infoArr.addObjects(from: (jsonArray["users"]![index] as! [String: Any])["info"] as! [Any]) 
} 
print("info arr : (infoArr)") 
for index in 0...1 { 
    idArr.addObjects(from: (jsonArray["users"]![index] as! [String: Any])["id"] as! [Any]) 
} 
print("id arr : (idArr)")

但我收到的错误如下:

  

无法转换类型' Swift._SwiftDeferredNSDictionary< Swift.String,Swift.String>' (0x1079b8420)到了NSArray' (0x106332008)

     

无法转换类型' Swift.Dictionary< Swift.String,Swift.String>' (0x1105ac550)到' Swift.Array< Any>' (0x1105abf30)。

     

无法转换类型的价值' Swift.Int' (0x11149f8c0)到' Swift.Array< Any>' (0x1114c4f30)。

3 个答案:

答案 0 :(得分:0)

1-改变这个

["info"] as! [Any]

["info"] as! [String:Any]

2-和这个

["id"] as! [Any]

["id"] as! NSNumber

//

var idArr = [NSNumber]()
var infoArr = [[String:Any]]()

for index in 0...1 { 
 infoArr.append((jsonArray["users"]![index] as! [String: Any])["info"] as! [String:Any]) 
} 
print("info arr : (infoArr)") 
for index in 0...1 { 
idArr.append((jsonArray["users"]![index] as! [String: Any])["id"] as! NSNumber) 
} 

答案 1 :(得分:0)

**Check correct code**


  var idArr = [Int]()
    var infoArr = [[String:Any]]()
    let usersArr = [Any]()

    for index in 0...1 {
        infoArr.append((jsonArray["users"]![index] as! [String: Any])["info"] as! [String:Any])
    }
    print("info arr : \(infoArr)")
    for index in 0...1 {
        idArr.append((jsonArray["users"]![index] as! [String: Any])["id"] as! Int)
    }
    print("id arr : \(idArr)")

答案 2 :(得分:-1)

试试这个:

var infoArr: [Any] = []
var idArr: [Any] = []

for i in 0..<(jsonArray["users"]!).count {
  infoArr.append((jsonArray["users"]![i] as! [String: Any])["info"])
  idArr.append((jsonArray["users"]![i] as! [String: Any])["id"])
}