Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift using String to create JSON object

Tags:

json

ios

swift

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?

like image 722
Jake Gearhart Avatar asked Jun 17 '26 02:06

Jake Gearhart


2 Answers

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.

like image 71
Claudio Redi Avatar answered Jun 18 '26 17:06

Claudio Redi


    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")
        }
    }
like image 45
James Takarashy Avatar answered Jun 18 '26 16:06

James Takarashy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!