解析包含"字符串数组"使用Swift 3.0进入Array

时间:2017-08-16 05:10:05

标签: swift

我正在寻找一种使用Swift 3.0将此字符串转换为数组的方法

let arrayString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"

// Should be converted into:

let array: [String] = [
    "One",
    "Two",
    "Three",
    "Four"
]

如果我使用,作为分隔符将其分隔为令牌,则会包含[],因此无法正常工作。如何正确转换?

注意:

问题不同于: Simple and clean way to convert JSON string to Object in Swift

我没有尝试转换其中包含多个键的JSON对象。

3 个答案:

答案 0 :(得分:7)

它是一个JSON字符串,你必须使用JSONSerialization在普通字符串数组中转换它。

Swift 3.0

func convertToArray(str: String) -> [String]? {

    let data = str.data(using: .utf8)

    do {
        return try JSONSerialization.jsonObject(with: data!, options: []) as? [String]
    } catch {
        print(error.localizedDescription)
    }

   return nil

 }

let aString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"

let arrayString = convertToArray(str: aString)

print(arrayString) // ["One", "Two", "Three", "Four"]

答案 1 :(得分:1)

可以通过多种方式实现您的目标,但我认为最简单的方法之一是:

let newArray = arrayString
 .replacingOccurrences(of: "[", with: "")
 .replacingOccurrences(of: "]", with: "")
 .replacingOccurrences(of: "\"", with: "")
 .components(separatedBy: ",")

输出应为:

["One", " Two", " Three", " Four"]

修改 正如@MartinR建议的那样,如果任何字符串包含逗号或方括号,则上一个答案不起作用。所以要解决这个问题,你可以删除方括号,假设在开头和结尾总是有,然后使用正则表达式匹配\"()\"内的所有内容,如下面的代码所示:

让我们使用以下函数来匹配正则表达式:

func matches(for regex: String, in text: String) -> [String] {
   do {
       let regex = try NSRegularExpression(pattern: regex)
       let nsString = text as NSString
       let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
       return results.map { nsString.substring(with: $0.range)}
   } catch let error {
       print("invalid regex: \(error.localizedDescription)")
       return []
   }
}

有关详情,请参阅@MartinR回答here

使用该功能,我们可以使用以下代码来实现我们想要的目标:

let str = "[\"One[\",\"T,w,o,\",\"Thr,ee,,,\",\"Fo,ur,,,\"]"

// remove the square brackets from the array
let start = str.index(str.startIndex, offsetBy: 1)
let end = str.index(str.endIndex, offsetBy: -1)
let range = start..<end
let newString = str.substring(with: range)

// match the regex 
let matched = matches(for: "(?<=\")(.*?)(?=\")", in: newString) // ["One[", ",", "T,w,o,", ",", "Thr,ee,,,", ",", "Fo,ur,,,"] 

但是之前的matched包含了数组中的",",所以让我们使用以下代码修复它:

let stringArray = matched.enumerated()
       .filter { $0.offset % 2 == 0 }
       .map { $0.element }

使用以下输出:

["One[", "T,w,o,", "Thr,ee,,,", "Fo,ur,,,"]

我希望这会对你有所帮助。

答案 2 :(得分:0)

以下是转换为数组的自定义代码:

var arrayString: String = "[\"One\", \"Two\", \"Three\", \"Four\"]"
arrayString = arrayString.replacingOccurrences(of: "[", with: "")
arrayString = arrayString.replacingOccurrences(of: "]", with: "")
arrayString = arrayString.replacingOccurrences(of: " ", with: "")
arrayString = arrayString.replacingOccurrences(of: "\"", with: "")
print("\(arrayString)")
var arr: [Any] = arrayString.components(separatedBy: ",")
print("\(arr)")

如果从API及其JSON获得上述字符串,则使用以下内容:

extension String {
    func toJSON(): Any? {
        guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
        return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    }
}