3

I am trying to use a string I am getting from a database as JSON using swift. I have tried to convert the string to a data object and then use JSONSerialization, but the results always come back nil.

Here is a sample of my code:

var string = "{Param1: \"Value\", Param2: \"value2\", Param3: \"value3\"}"
let data = (reducedOptionsString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
if let d = data{
    var err : NSErrorPointer = nil
    let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.MutableLeaves, error: err)
    if let dict = parsedObject as? Dictionary<String, AnyObject>{
          ...
    }
}

For some reason parsedObject always comes back as nil

Does anyone know what I might be missing to convert my string data to a JSON object that I can use?

2
  • Why are you ignoring the error parameter? Print it out on failure. Commented Jun 18, 2015 at 3:58
  • The code is incorrect, string is not used and reducedOptionsString is undefined. I guess they are the same. Commented Jun 18, 2015 at 4:09

4 Answers 4

5

Your json is not valid, keys must me enclosed in quotes too.

"{ \"Param1\": \"Value\", \"Param2\": \"value2\", \"Param3\": \"value3\"}"

Also, as @zaph pointed out, it's variable string the one you want to convert to data.

var string = "{\"Param1\": \"Value\", \"Param2\": \"value2\", \"Param3\": \"value3\"}"
if let data = string.dataUsingEncoding(NSUTF8StringEncoding){
    var err : NSErrorPointer = nil
    let parsedObject = NSJSONSerialization.JSONObjectWithData(
        data!,
        options: NSJSONReadingOptions.MutableLeaves, 
        error: err) as? Dictionary<String, AnyObject>

    if (parsedObject != nil) {
        ...
    }
    else {
        if (err != nil) {
            println("Error: \(err)")
        }
        else {
            println("Error: unexpected error parsing json string")
        }
    }
}

Alternatively, you could use SwiftyJSON, a very popular library to handle json on swift that could make your life a little easier.

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

Comments

3
    var string = "{\"Param1\": \"Value\", \"Param2\": \"value2\", \"Param3\": \"value3\"}"

    if let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    {
        var err : NSErrorPointer = nil
        let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:    NSJSONReadingOptions.MutableLeaves, error: err)

        if (err != nil)
        {
            println("error handling...")
        }

        if let dict = parsedObject as? Dictionary<String, AnyObject>
        {
            println("XD")
        }
    }

1 Comment

Hehehehe :), just a smiley since I can't stand empty if statements in code and writing "..." will force you to replace this line when copying to your project, even if you just wanted to test if it compiles... So, it makes life easier, just by a little bit ;)
1

You just replace following 2 lines in your OWN code, rest will be work fine. :)

var string = "{\"Param1\": \"Value\", \"Param2\": \"value2\", \"Param3\": \"value3\"}"
let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)

Comments

1

Swift 5 Example:

let properties: [(String, Any?)] = [("firstName", firstName),
                                        ("lastName", lastName),
                                        ("city", city),
                                        ("state", state),
                                        ("zipCode", zipCode),
                                        ("country", country)]

let body = properties.compactMap({ property -> (String, Any)? in
        if let value = property.1 {
            return (property.0, value)
        } else {
            return nil
        }
    })

let jsonDict = Dictionary(uniqueKeysWithValues: body)
let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict, options: [])

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.