json转换为数组swift

时间:2017-03-17 19:40:40

标签: arrays json swift nsjsonserialization

我从服务器那里得到这样的json:

array('id' => '1', 'name' => 'Radni nalog 1', 'threadTypeList' => array(
            array('id' => '1', 'name' => 'Crvena'), 
            array('id' => '2', 'name' => 'Plava'), 
            array('id' => '3', 'name' => 'Zelena'), 
            array('id' => '4', 'name' => 'Žuta'), 
        ), 'token' => 'xxuoE73VKwyKk1KmGTy26P72cgsuneMzNOes');

如何将此json转换为字典。这是我的转换功能,但它完全错了,我坚持使用它。

func convertStringToDictionary2(text: String) -> [AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

当我尝试获取这样的数据时:

    let result = convertStringToDictionary(jsonString as String)

//creating array of objects threadType and populating threadTypeList property
let resultThreadList = (result?["threadTypeList"] as! String)

let new = convertStringToDictionary2(resultThreadList as String)

我收到错误:无法转换类型' __ NSArrayI' (0x10f20dd88)到' NSString' (0x10df90c40)。

我能从json获取所有变量,除了** threadTypeList **,这是一个数组数组。

1 个答案:

答案 0 :(得分:0)

错误

  

无法将'__NSArrayI'(0x10f20dd88)类型的值转换为'NSString'(0x10df90c40)

表示:

您要访问的对象是 Array ,但您希望获得 String ,这是不可能的

let resultThreadList = result?["threadTypeList"] as! [[String:AnyObject]]

resultThreadList表示数组以及PHP类型'threadTypeList' => array(,但认为PHP(关联)数组 array('id' => '1'实际上是字典。