0

After decrypting my response from API i am getting a string "name:DM100, profile:[1,2,4,5]".

How can i convert this to a json object where name is string and profile is an array

i have tried using but getting nil

if let data = testString.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print("JSON Serialization Error :-> \(error.localizedDescription)")
        }
    }
    return nil
}
1
  • 2
    You can't use JSONSerialization because the string is not valid JSON. All keys and other strings must be wrapped in double quotes. Commented May 24, 2019 at 5:06

2 Answers 2

1

Your JSON String is not valid. It should look like this:

let testString = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"

if let data = testString.data(using: .utf8) {
    do {
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            print(json["name"])
        }
    }
    catch {
        print(error.localizedDescription)

    }
}

Start and end with curly braces {} and have double quotations around string keys and values.

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

Comments

0

You can use following code to get the output:

But String must have and valid JSON format first as follows:

 let string = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"
            let data = string.data(using: .utf8)!
            do {
                if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any> {
                    print(jsonObj)
                } else {
                    print("JSON Error")
                }
            } catch let error as NSError {
                print(error)
            }

Comments

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.