我正在使用swiftjson(https://github.com/lingoer/SwiftyJSON)遍历下面的json:

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

我正试图循环通过codes块。到目前为止我在尝试:
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)
        }

    }

我不确定我做的是否正确。我应该如何正确地循环dataArray,或者也许有一种比我尝试的更好的循环方式?
除了使用swiftjson之外,我还尝试使用下面的方法来解析json,但是我不知道如何循环遍历这些项:
func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

    return boardsDictionary
}

如果这两种方法都奏效的话,那将是有帮助的。

最佳答案

{  "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"}]}]}

上面给出了json的snippit。我用swiftyjson进行解析,如下所示:
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)
    }
}

关于json - 使用swiftyjson遍历对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26020094/

10-11 01:17