简体   繁体   中英

Swift 4 parse string to json object

I have implement qr code scanner, Where in "metadataOutput" delegate method I have received response which has key like "stringValue", Value of this key is

stringValue "'{ "part_number":"154100102232", "lot_number":"03S32401701344"}'"

I want parse string value to json object, but I am not able to do that.

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

I have followed above approach to parse string to json, but I have found following error.

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

Can anyone have any idea about this?

Better have an extension to String like this

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

Use like this

let dict = stringValue.toDcitionary()

Or you can use pod for all these kind of work from UtilityKit on github https://github.com/utills/UtilityKit

This works with me , You string has ' character around trailing "' content '"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM