我有一个像这样的JSON字符串:
let stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
如何在此字符串中删除一个项目(例如,tommy)?
我尝试将其投放到[[NSObject: AnyObject]]
,但总是失败。
if let dictArray = stringArray as? [[NSObject: AnyObject]] {
} else {
println("failed") // print failed.
}
我如何得到这样的结果:
[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25}]
答案 0 :(得分:0)
首先将您的json字符串转换为swift数组或字典;
let stringArray:String = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
let data:NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!;
let dict:NSArray = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSArray;
NSLog("dict \(dict)");
答案 1 :(得分:0)
也许您可以将原始的jsons字符串转换为字典然后选择您需要的密钥。作为示例代码,如:
if let json = NSJSONSerialization.JSONObjectWithData("your string to NSDATA",options:NSJSONReadingOptions.AllowFragments,$error){
// checks the son type and make sure the operation perform to the NSDictionary
var d = json as! NSDictionary;
// Picks the the values your want from d
}
答案 2 :(得分:0)
将字符串转换为数组,因为它的JSON字符串
var stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
var data : NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var error: NSError?
var array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as Array<AnyObject>
println(array)
输出:
[{
age = 25;
name = benson;
url = "www.abc.com";
}, {
age = 23;
name = tommy;
url = "www.abc.com";
}]
现在执行删除操作
array.removeAtIndex(1)
println(array)
输出:
[{
age = 25;
name = benson;
url = "www.abc.com";
}]