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?

2
  • It seems like you have some invalid charcter in string. Ask backend developer to provide it in a valid format and use jsonObject(with: data, options: []). Commented May 28, 2018 at 9:12
  • ask your backend service if he is giving you the jsonString Commented May 28, 2018 at 9:15

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great solution.
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.
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)
    }

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.