我从服务器收到一个JSON字符串,它看起来像这样:
[[{\"type\":\"action\",\"action\":\"courier_on_map\",\"text\":\"\\u0421\\u043c\\u043e\\u0442\\u0440\\u0435\\u0442\\u044c \\u043d\\u0430 \\u043a\\u0430\\u0440\\u0442\\u0435\"}]]
Web解析器说“JSON字符串有效,但JSON数据不准确”。然而,JSONSerialization说:
字符1周围的对象中的值没有字符串键
并返回错误。
代码:
func convertToNSDictionary() -> NSDictionary?
{
var string = self
string = string.replacingOccurrences(of: "[", with: "")
string = string.replacingOccurrences(of: "]", with: "")
if let data = string.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
} catch {
print(error.localizedDescription)
}
}
return nil
}
答案 0 :(得分:0)
不要手动操作原始JSON字符串。
假设您的代码位于String
的扩展名内,请执行以下操作:
let str = "[[{\"type\":\"action\",\"action\":\"courier_on_map\",\"text\":\"\\u0421\\u043c\\u043e\\u0442\\u0440\\u0435\\u0442\\u044c \\u043d\\u0430 \\u043a\\u0430\\u0440\\u0442\\u0435\"}]]"
extension String {
func convertToDictionary() -> [String:Any]? {
let str = self
guard let data = str.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [[[String:Any]]]
else {
return nil
}
//debug prints
print(json)
let innerArray = json.first!
print(innerArray)
let dict = innerArray.first!
print(dict)
if let type = dict["type"] {
print(type)
}
//
return dict
}
}
let dict = str.convertToDictionary()
print(dict)
打印:
[[["type": action, "action": courier_on_map, "text": Смотреть на карте]]]
[["type": action, "action": courier_on_map, "text": Смотреть на карте]]
["type": action, "action": courier_on_map, "text": Смотреть на карте]
action
Optional(["type": action, "action": courier_on_map, "text": Смотреть на карте])
如果你真的需要一个NSObject
,你可以施展它:
let nsDict = dict! as NSDictionary