我有一个这样的字符串:
let arrayString : String = "[[1, 123, 0], [4, 003, 21]]"
我想将此字符串转换为以下类型的二维数组:[[String]]
。
我尝试使用类似这样的行:
var array : [[String]] = arrayString as! [[String]]; // abort error
还有类似这样的东西:
if let json = try? JSONSerialization.jsonObject(with: ucode.data(using: .utf8)!, options: []) {
let array = json as! [[String]];
print(array[0][0]) // prints nothing --> just ""
}
<小时/>
So I got no idea how I could solve this problem to convert:
"[[1, 123, 0], [4, 003, 21]]" ----> [["1", "123", "0"], ["4", "003", "21"]]
任何帮助将不胜感激,提前一百万致谢。
最佳答案
基本上这个字符串是 JSON,但序列化程序提示前导零。
解决方案是在反序列化 JSON 之前添加双引号,将整数值转换为 String
。这可以通过正则表达式简单地实现
let arrayString = "[[1, 123, 0], [4, 003, 21]]"
let convertedArrayString = arrayString.replacingOccurrences(of: "\\d+", with: "\"$0\"", options: .regularExpression)
let data = Data(convertedArrayString.utf8)
do {
if let array = try JSONSerialization.jsonObject(with: data) as? [[String]] {
print(array)
}
} catch { print(error)}
关于arrays - 转换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840088/