Swift 3 Accessing JSON data stored in dictionary

In my ios app I'm allowing the user to create a group. Whenever they create a group the group JSON values from my php file is returned and stored in a dictionary called groups:


var groups : NSDictionary?


How can I access a value from this dictionary? For example if a group has an Id of 1, how can I pull all of the data from group 1? Sorry I'm very new to swift.

Answered by Claude31 in 255067022

Your json return data with key : value : you should see in php script for instance what are key and value.

If keys are STrings as Key1, Key2, … and values are Strings

You should have code like this (of course need to adapt to your real json data definition):


                var groups : NSDictionary?   /
                do {
                    let aDictionary : NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                    if let actualDictionary = aDictionary {
                        groups = actualDictionary
                    }
                    else {
                        // aDictionary is nil
                    }
                }
                catch {
                    print("Error ", error)
                }
                if let parseJSON = groups {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
           
                    if let value1 = parseJSON["key1"] as? String { // You have recovered the data from group 1
Accepted Answer

Your json return data with key : value : you should see in php script for instance what are key and value.

If keys are STrings as Key1, Key2, … and values are Strings

You should have code like this (of course need to adapt to your real json data definition):


                var groups : NSDictionary?   /
                do {
                    let aDictionary : NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                    if let actualDictionary = aDictionary {
                        groups = actualDictionary
                    }
                    else {
                        // aDictionary is nil
                    }
                }
                catch {
                    print("Error ", error)
                }
                if let parseJSON = groups {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
           
                    if let value1 = parseJSON["key1"] as? String { // You have recovered the data from group 1
var groups : NSDictionary?

Personally I try to stay away from

NSDictionary
whenever possible, preferring Swift native types. For example:
import Foundation

let jsonData = """
    {
        "groupID": 42,
        "groupName": "DeepThinkers"
    }
    """.data(using: .utf8)!

struct Group {
    var groupID: Int
    var groupName: String
}

func testJSONSerialization() {
    guard let jsonDict = (try? JSONSerialization.jsonObject(with: jsonData)) as? [String:Any] else {
        print("handle format error")
        return
    }
    guard let groupID = jsonDict["groupID"] as? Int else {
        print("handle format error")
        return
    }
    guard let groupName = jsonDict["groupName"] as? String else {
        print("handle format error")
        return
    }
    let group = Group(groupID: groupID, groupName: groupName)
    print(group)    // prints 'Group(groupID: 42, groupName: "DeepThinkers")'
}

Or, better yet, use Swift 4’s shiny new automatic coding support.

struct Group : Codable {
    var groupID: Int
    var groupName: String
}

func testCodable() {
    let decoder = JSONDecoder()
    guard let group = try? decoder.decode(Group.self, from: jsonData) else {
        print("handle format error")
        return
    }
    print(group)    // prints 'Group(groupID: 42, groupName: "DeepThinkers")'
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

As usual, great advices !


I'm not yet using Swift4. But clearly, jsonDecoder will make it much simpler.


Note: NSDictionary came from Swift2 vbersion of a code that was automatically translated in NSDictionary as well. I'll have to get rid progressively of those legacy.

Swift 3 Accessing JSON data stored in dictionary
 
 
Q