[英]Swift 4 parse string to json object
我已經實現了二維碼掃描器,在“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,但發現以下錯誤。
錯誤域=NSCocoaErrorDomain 代碼=3840 “字符 0 周圍的值無效。” UserInfo={NSDebugDescription=字符 0 周圍的值無效。}
任何人都可以對此有任何想法嗎?
最好像這樣對 String 進行擴展
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 上的UtilityKit 中使用 pod 來完成所有這些類型的工作
這對我有用,你的字符串在尾隨"'
內容'"
周圍有'
字符
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.