我已经实现了二维码扫描器,其中在"metadataOutput“委托方法中,我收到了类似于"stringValue”键的响应,这个键的值是
stringValue "'{ "part_number":"154100102232",“lot_number”:“03S32401701344”}“”
我希望将字符串值解析为json对象,但我无法做到这一点。
let data = stringValue.data(using: .utf8)!
do {
if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [AnyHashable:Any]
{
print("Json:::",json)
// post a notification
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SCANNER_DATA"), object: nil, userInfo: json)
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
我按照上面的方法将字符串解析为json,但我发现了以下错误。
Error Domain=NSCocoaErrorDomain Code=3840“字符0周围的值无效。”UserInfo={字符0周围的NSDebugDescription=Invalid值。}
有人知道这是怎么回事吗?
发布于 2018-05-28 18:24:16
最好有一个像这样的字符串扩展
extension String{
func toDictionary() -> NSDictionary {
let blankDict : NSDictionary = [:]
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
} catch {
print(error.localizedDescription)
}
}
return blankDict
}
}
像这样使用
let dict = stringValue.toDcitionary()
或者你可以在github https://github.com/utills/UtilityKit上使用pod来完成所有这些工作。
发布于 2018-05-28 17:14:04
这与我的工作,您的字符串有'
字符周围的尾随"'
内容'"
let stringValue = """
{"part_number":"154100102232","lot_number":"03S32401701344"}
"""
let data = stringValue.data(using: .utf8)!
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any]
{
print("ewtyewytyetwytewytewtewytew",json)
} else {
print("ewtyewytyetwytewytewtewytew","bad json")
}
} catch let error as NSError {
print("ewtyewytyetwytewytewtewytew",error)
}
https://stackoverflow.com/questions/50562747
复制相似问题