我如何解析这个respose到我的字符串数组

时间:2017-05-30 10:32:13

标签: ios arrays swift

var mobileOprator = [String]() // My Array

//My Response
Optional("[\n  \"Aircel\",\n  \"Airtel\",\n  \"BSNL\",\n  \"Idea MTV\",\n  \"MTNL\",\n  \"MTS\",\n  \"Reliance CDMA\",\n  \"Reliance GSM\",\n  \"Reliance JIO\",\n  \"TATA CDMA\",\n  \"TATA DOCOMO\",\n  \"Telenor\",\n  \"Videocon\",\n  \"Vodafone\"\n]")

我想将它解析为我的mobileOprator数组。

2 个答案:

答案 0 :(得分:1)

Optional("[\n  \"Aircel\",\n  \"Airtel\",\n  \"BSNL\",\n  \"Idea MTV\",\n  \"MTNL\",\n  \"MTS\",\n  \"Reliance CDMA\",\n  \"Reliance GSM\",\n  \"Reliance JIO\",\n  \"TATA CDMA\",\n  \"TATA DOCOMO\",\n  \"Telenor\",\n  \"Videocon\",\n  \"Vodafone\"\n]")

与此相同,只是为了更好地可视化数据

Optional("[  
              \"Aircel\",
              \"Airtel\",
              \"BSNL\",
              \"Idea MTV\",
              \"MTNL\",
              \"MTS\",
              \"Reliance CDMA\",
              \"Reliance GSM\",
              \"Reliance JIO\",
              \"TATA CDMA\",
              \"TATA DOCOMO\",
              \"Telenor\",
              \"Videocon\",
              \"Vodafone\"
            ]")

由于数据是可选的,我们应检查它是否存在以及它是否开始解析。这可以使用以下语法完成:

if let a = optional_a {

}

其中optional_a可以是任意可选数据类型,anonoptional。基本上Swift检查它是nil,如果不是a

接下来,对于解析,String类有一个名为replacingOccurences(of: String!, with String!)的函数。将此视为查找并替换所有功能。这可用于删除任何无关的字符,例如" \ n"," \""," \"," [ ","]"," &#34 ;.删除后,我们需要将字符串拆分为","并将其映射到数组中。

此代码应该有效:

var optionalResponse = Optional("[\n  \"Aircel\",\n  \"Airtel\",\n  \"BSNL\",\n  \"Idea MTV\",\n  \"MTNL\",\n  \"MTS\",\n  \"Reliance CDMA\",\n  \"Reliance GSM\",\n  \"Reliance JIO\",\n  \"TATA CDMA\",\n  \"TATA DOCOMO\",\n  \"Telenor\",\n  \"Videocon\",\n  \"Vodafone\"\n]")
if var response = optionalResponse {
    let charsToRemove = ["\n", "\"", "\\", "[", "]", " "]
    for char in charsToRemove {
        response = response.replacingOccurrences(of: char, with: "")
    }
    let fullNameArr = response.characters.split{$0 == ","}.map(String.init)

    print(fullNameArr)
}

答案 1 :(得分:0)

if let dataa = data as? String{
                if let dataFromString = dataa.data(using: String.Encoding.utf8, allowLossyConversion: false) {
                    let json = JSON(data: dataFromString)
                    for (_, val) in json {
                        self.mobileOprator.append(val.rawString()!)
                    }
                }
            }

通过这种方式,我得到了我想要的数组,使用 SwiftyJSON 进行解析..