json 转换为数组 swift
json converting to array swift
我从服务器得到这样的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** 除外,它是一个数组数组。
错误
Could not cast value of type '__NSArrayI' (0x10f20dd88) to 'NSString' (0x10df90c40)
表示:
你要访问的对象是Array
但是你想得到一个String
这是不可能的.
let resultThreadList = result?["threadTypeList"] as! [[String:AnyObject]]
resultThreadList
暗示数组以及 PHP 类型 'threadTypeList' => array(
但考虑 PHP (关联) array array('id' => '1'
实际上是一个字典
我从服务器得到这样的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** 除外,它是一个数组数组。
错误
Could not cast value of type '__NSArrayI' (0x10f20dd88) to 'NSString' (0x10df90c40)
表示:
你要访问的对象是Array
但是你想得到一个String
这是不可能的.
let resultThreadList = result?["threadTypeList"] as! [[String:AnyObject]]
resultThreadList
暗示数组以及 PHP 类型 'threadTypeList' => array(
但考虑 PHP (关联) array array('id' => '1'
实际上是一个字典