Swift 4解析字符串到json对象

时间:2018-05-28 09:07:44

标签: ios json swift parsing qr-code

我已经实现了qr代码扫描程序,其中在“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。}

有人可以对此有任何想法吗?

2 个答案:

答案 0 :(得分:2)

最好像这样

扩展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/ervivek40/UtilityKit

上使用pod来进行所有这些工作。

答案 1 :(得分:1)

这适用于我,您的字符串'字符"'内容'"

   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)
    }