-1

How can I access data from a nested dictionary - when I want to save all data from "CourseDates”? CourseDates = NSArrayM

json

let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

if let test = json[0]["CourseDates"] as? [[String : AnyObject]] {
// heres my problem
 }
qetinac
  • 53
  • 2
  • 7

3 Answers3

3

You can create a function that returns NSDictionary like this:

func parseJSON(data: NSData) -> NSDictionary{
        var dic: NSDictionary!
        do {
            boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        } catch let error as NSError {
            print(error.localizedDescription)
            print("Error could not parse JSON data, it's null maybe?!!")
        }
        //'\(jsonStr)'

        return dic
    }

UPDATE:

Add This:

public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}

let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary
firats
  • 496
  • 2
  • 7
  • it didnt work - i got this error > Could not cast value of type '__NSArrayM' (0x10eb32b60) to 'NSDictionary' (0x10eb32fe8). – qetinac Jul 21 '16 at 11:04
  • Maybe you should convert your json data to NSData this link looks well: [link](http://stackoverflow.com/questions/26840736/converting-json-to-nsdata-and-nsdata-to-json-in-swift) – firats Jul 21 '16 at 11:29
1

Hi you can try SwiftyJson, It is a great source through which you can deal with complex JSON in a much more simpler way then you ever thought. For example { "metadata":{ "responseInfo":{ "status":200, "developerMessage":"OK", } }, "results":[ { "title":"Legal immigrants should get freedom before undocumented immigrants – moral, just and fair", "body":"I am petitioning President Obama's Administration to take a humane view of the plight of legal immigrants. Specifically, legal immigrants in Employment Based (EB) category. I believe, such immigrants were short changed in the recently announced reforms via Executive Action (EA), which was otherwise long due and a welcome announcement.", "issues":[ { "id":"28", "name":"Human Rights" }, { "id":"29", "name":"Immigration" } ], "signatureThreshold":100000, "signatureCount":267, "signaturesNeeded":99733, }, { "title":"National database for police shootings.", "body":"There is no reliable national data on how many people are shot by police officers each year. In signing this petition, I am urging the President to bring an end to this absence of visibility by creating a federally controlled, publicly accessible database of officer-involved shootings.", "issues":[ { "id":"28", "name":"Human Rights" } ], "signatureThreshold":100000, "signatureCount":17453, "signaturesNeeded":82547, } ] }

From this JSON if you want to extract the result you can do easily like this

func parseJSON(json: JSON) {
for result in json["results"].arrayValue {
    let title = result["title"].stringValue
    let body = result["body"].stringValue
    let sigs = result["signatureCount"].stringValue
    let obj = ["title": title, "body": body, "sigs": sigs]
    objects.append(obj)
}

}

1

Here is the simple example how can we extract data from the NSDictionary. And this is simple and i'm not following any standards...

I considered json data in String format.

var data = "{\"data\":{\"fName\":\"naveen\",\"lName\":\"kumar\"},\"friend\":[{\"name\":\"manju\",\"male\":true},{\"name\":\"tanuja\",\"male\":false}]}"

After that you can do

var nsdata = data.dataUsingEncoding(NSUTF16StringEncoding)
if let json = try? NSJSONSerialization.JSONObjectWithData(nsdata!, options: .MutableContainers) as! NSDictionary {         
    if let some = json["friend"]![0]["name"]! {
        print(some) // prints -- manju
    }
}

By using the subscipt we can get the data.

Naveen Kumar H S
  • 1,304
  • 16
  • 30