Mirza Delic
Mirza Delic

Reputation: 4339

SwiftyJSON.JSON to [String: AnyObject]

How can i make [String: AnyObject] from JSON?

let jsonString = Mapper().toJSONString(article!)

// {\"price\":\"220.00\",\"name\":\"Capricciosa\",\"active\":true,\"calculable\":true,\"id\":76,\"article_type\":2,\"ingredients\":[],\"critical_qty\":\"0.00\",\"barcode\":\"\",\"tax\":\"1\"}


let json = SwiftyJSON.JSON(jsonString!)
// i need here to get [String: AnyObject]

need this for Alamofire parametres..

Upvotes: 2

Views: 3982

Answers (3)

Christian1313
Christian1313

Reputation: 268

You can access the dictionaryObject direct from the SwiftyJSON json

    let dict: [String: AnyObject]
    if jDict = json.dictionaryObject {
        dict = jDict
    } else {
        dict = [String: AnyObject]()
    }

Upvotes: 4

Kametrixom
Kametrixom

Reputation: 14973

SwiftyJSON is actually just a wrapper around the NSJSONSerialization in Foundation, it just makes it more convenient to access the values and dig down in the structure. However that's not what you actually want to do, you only need the dictionary which is just what NSJSONSerialization returns. If you'd use SwiftyJSON for that, you'd just be taking the long route.

This function does what you need without SwiftyJSON:

func jsonDict(json: String) -> [String : AnyObject]? {
    if let
        data = json.dataUsingEncoding(NSUTF8StringEncoding),
        object = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
        dict = object as? [String : AnyObject] {
            return dict
    } else {
        return nil
    }
}

Or if you prefer a more functional approach:

func jsonDict(json: String) -> [String : AnyObject]? {
    return json.dataUsingEncoding(NSUTF8StringEncoding)
        .flatMap{ try? NSJSONSerialization.JSONObjectWithData($0, options: []) }
        .flatMap{ $0 as? [String : AnyObject] }
}

Upvotes: 2

Darko
Darko

Reputation: 9845

Do it like this:

    let jsonString = "{\"price\":\"220.00\",\"name\":\"Capricciosa\",\"active\":true,\"calculable\":true,\"id\":76,\"article_type\":2,\"ingredients\":[],\"critical_qty\":\"0.00\",\"barcode\":\"\",\"tax\":\"1\"}"
    var dict = [String: AnyObject]()
    if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
        let json = JSON(data: dataFromString)
        for (key, value) : (String, JSON) in json {
            dict[key] = value.object
        }
    }

Upvotes: 2

Related Questions