1

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?

nadim
  • 776
  • 1
  • 12
  • 26

2 Answers2

3

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

Vivek Kumar
  • 405
  • 5
  • 15
  • 1
    Great solution. – ironRoei Nov 05 '18 at 12:51
  • 1
    You are strongly discouraged from using a library which suggests Foundation types `NSArray/NSDictionary` rather than Swift native types. You are fighting the strong type system. – vadian Nov 05 '18 at 13:08
1

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)
    }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Thank you for the reply, Yes you are right if I used two " then it works fine, But unfortunately I have " following '. As a result it was not worked.Any way I have found solution. I have check in string first and last character if it start with " ' " then remove it and then parse. – nadim May 28 '18 at 09:45