将复杂的字符串转换为数组

时间:2016-04-06 06:26:29

标签: swift nsstring nsarray

我有一个字符串如下

[["3254","CCH"],["001","Sulmatyl 50mg","Sulpiride",[0,0,0,0,1],28,0.5],["002","Knowful 1.2g","Piracetam",[1,0,0,0,0],28,1],["003",Tranexamic acid 250mg","Tranexamic acid",[0,3,3,3,0],7,1],["004","Isormol 20mg","Isosorbide mononitrate",[0,3,0,3,0],28,0.5],["005","Plavix 75mg","Clopidogrel",[1,0,0,0,0],28,1]]

如何将此字符串转换为数组? 所以它就像

[

["3254","CCH"],  // pres[0]
["001","Sulmatyl 50mg","Sulpiride",[0,0,0,0,1],28,0.5], //pres[1]
["002","Knowful 1.2g","Piracetam",[1,0,0,0,0],28,1], //pres[2]
["003",Tranexamic acid 250mg","Tranexamic acid",[0,3,3,3,0],7,1], //pres[3]
["004","Isormol 20mg","Isosorbide mononitrate",[0,3,0,3,0],28,0.5], //pres[4]
["005","Plavix 75mg","Clopidogrel",[1,0,0,0,0],28,1] //pres[5]

]

1 个答案:

答案 0 :(得分:0)

您正在寻找非常低级且复杂的解析,但是将[转换为(]转换为)并解析为JSON主要可用:

let newString = inputString.stringByReplacingOccurrencesOfString("[", withString: "(", options: NSStringCompareOptions.LiteralSearch, range: nil)
let newString = newString.stringByReplacingOccurrencesOfString("]", withString: ")", options: NSStringCompareOptions.LiteralSearch, range: nil)
let data = newString.dataUsingEncoding(NSUTF8StringEncoding)
do {
    let rootObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
    // done 
} catch {
    print("error serializing JSON: \(error)")
}

为获得最佳效果,请使用XML或JSON进行序列化,并避免使用定制格式,除非您愿意将这些工作放入解析中。