我在swift 3中解析json数据。这是结果的结构。 我需要将这个括号内容分开并将它们放入一个数组中。
(
{
name:"devin,patrick";
}
,
{
name:"devin,kalvin";
}
,
{
name: "devin,nic";
}
)
这是代码,
//parsing json data
if let jsonparsed = content as? NSDictionary {
if let neededData = jsonparsed["data"] {
print(neededData)
let exactData = String(describing:neededData)
let gotData = exactData.components(separatedBy: ",")
}
}
我将数据转换为字符串并尝试用逗号分隔内容,因为名称也有逗号,所以它不能正常工作,我需要将逗号覆盖的内容分开,任何帮助都会很棒。
答案 0 :(得分:1)
序列化你的json字符串后,获取一个Dictionary列表,获取每个字典的名称,然后执行componentsSeparatedBy你得到每个名字
if let data = text.data(using: .utf8) ,
let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: String]{
let array = dict.flatMap({$0["name"]}) //return ["devin,patrick", "devin,kalvin", "devin,nic"]
let names = array.flatMap({$0.components(separatedBy: ",")}) //return ["devin" ,"patrick" ,"devin" ,"kalvin" ,"devin" ,"nic"]
let uniqueNames = Set(names) // return ["nic", "patrick", "devin", "kalvin"]
}