我从服务器那里得到了json数据。
[
"http:\/\/helloWord.com\/user\/data\/000001.jpg?1497514193433",
"http:\/\/helloWord.com\/user\/data\/000002.jpg?1500626693722"
]
我应该怎样做才能得到每个用户的网址?
我尝试使用removingPercentEncoding
,但它不起作用
我该怎么办?
感谢。
let string:String = chatroom.avatar
let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()
print("**tempArr\(tempArr)")
for a in tempArr {
var b = a.replacingOccurrences(of: "\"", with: "")
b = b.replacingOccurrences(of: "[", with: "")
b = b.replacingOccurrences(of: "]", with: "")
b = b.removingPercentEncoding //not working!!!!
print("b: \(b)")
//b: http:\/\/helloWord.com\/user\/data\/000001.jpg?1497514193433
//b: http:\/\/helloWord.com\/user\/data\/000002.jpg?1500626693722
}
我使用swiftyJson
class User : Model {
var url:String = ""
func fromJson(_ json:JSON) {
url = json["url"].zipString
saveSqlite()
}
}
extension JSON {
var prettyString: String {
if let string = rawString() {
return string
}
return ""
}
var zipString: String {
if let string = rawString(.utf8, options: JSONSerialization.WritingOptions.init(rawValue: 0)) {
return string
}
return ""
}
}
答案 0 :(得分:0)
呃,你不应该尝试编写自己的JSON解析器。
尝试:https://github.com/SwiftyJSON/SwiftyJSON 它是Swift代码的一个文件,使得在Swift中使用JSON变得更加容易。 在swift 4中,您将能够使用Structs直接解码,但我们还没有。
苹果方式:
func read(payload: Data) throws -> [String]? {
guard let result = try JSONSerialization.jsonObject(with: payload, options: JSONSerialization.ReadingOptions.allowFragments) as? [String] else { return nil }
return result
}
然后例如你可以用这种方式阅读它们:
var userURLs: [URL] = []
for jsonURL in result {
guard let userURL = URL(string: jsonURL) else { continue }
userURLs.append(userURL)
}
这样,您只能获得上一个结果数组中的有效URL对象。
如果您在使用我上面描述的JSONSerialization代码时遇到问题,可能是它需要不同的类型。然后,您必须使用[Any]作为强制转换,或者如果您有对象[String:Any]通常有效。请记住,在这种情况下,您必须像这样强制转换从数组中获取的对象:
URL(string: (jsonURL as? String) ?? "")
Swifty JSON使得更容易实现可空性,因为它提供了一种安全遍历对象树并返回空但非零值的简单方法!
答案 1 :(得分:0)
在我看来,您想使用removingPercentEncoding
删除转义字符 - 那些反斜杠?虽然removingPercentEncoding
适用于百分比编码字符,例如将http%3A%2F%2Fwww.url-encode-decode.com%2F
转换为http://www.url-encode-decode.com/
。所以你在错误的地方使用它。确保仅对百分比编码的URL调用此方法。
对于这种情况,与其他已经建议过的情况一样,使用JSONSerialization
是可行的方法。