Tarang
Tarang

Reputation: 75955

Loop through objects with swiftjson

I'm using SwiftJSON (https://github.com/lingoer/SwiftyJSON) to loop through the json below:

{
    "response": {
        "codes": [
            {
                "id": "abc",
                "name": "Bob Johnson"
            },
            {
                "id": "def",
                "name": "Benson"
            }
        ]
    }
}

I'm trying to loop through the codes block. So far I'm trying:

let json = JSON(data: getJSON("<json_url>"))

    var people = json["response"]["codes"]

    let dataArray = nearBy.arrayValue!;

    println("Data items count: \(dataArray.count)")

    for item: AnyObject in dataArray {

        if let userName = item["name"].string{
            //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety
            println("Value" + userName)
        }

    }

I'm not sure I'm doing this correctly. How would I correctly loop through dataArray, or perhaps there is a better way of looping through than i'm trying?

In Addition to using SwiftJSON, i've also tried using the method below to parse the JSON, but I don't know how to loop through the items:

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

    return boardsDictionary
}

It would be helpful if either way worked.

Upvotes: 1

Views: 2859

Answers (2)

WhiteEagle
WhiteEagle

Reputation: 107

Here is the solution that I would use to loop through your JSON's "codes" and get (or print) each person's name...

let = JSON(data : myData)

if let codes = json["response"]["codes"].array {
    for eachCode in codes {
        let name = eachCode["name"]
        print("Name: \(name)")
        // or do whatever you'd like with each 'name'
    }
}

This is all you should need. I wouldn't bother with the other stuff you've tried using. I hope this will help you out.

Upvotes: 1

nwales
nwales

Reputation: 3561

{  "callout":{  "title":"Callout title","image":"http://image","url":"http://callouturl"},"categories":[  {  "category":"Category 1","articles":[  {  "title":"title 1","image":"image 1","url":"http://url1.com"},{ "title":"title 2","image":"image 2","url":"http://url2.com"}]},{  "category":"Category 2","articles":[  { "title":"title 3","image":"image 3","url":"http://url3.com"},{ "title":"title 4","image":"image 4","url":"http://url4.com"}]}]}

Given the snippit of JSON above. I parse with SwiftyJSON like so:

let json:JSON = JSON(data:myData)

var catCollections:[CategoryCollection] = []

//gather category collections of articles
for (index: String, cat: JSON) in json["categories"] {

    //collect articles within each category
    var articles:[ArticleItem] = []
    for(index:String, art:JSON) in cat["articles"] {
        let artTitle = art["title"].string
        let artImage = art["image"].string
        let artUrl = art["url"].string

        if(artTitle != nil && artUrl != nil) {
            let articleItem = ArticleItem(title: artTitle!, url: artUrl!, imageURL: artImage)
            articles.append(ArticleItem)
        }

    }

    //create category collection for each category
    let catTitle = cat["category"].string ?? ""
    let catCollection = CategoryCollection(title: catTitle, articles: articles)
    catCollections.append(catCollection)
}

var callout:CalloutItem?
//check for existance of callout item
if let calloutTitle = json["callout"]["title"].string {
    if let calloutUrl = json["callout"]["url"].string {
        callout = CalloutItem(title: calloutTitle, url: calloutUrl, imageURL: json["callout"]["image"].string)
    }
}

Upvotes: 2

Related Questions