用swiftyjson循环遍历对象

时间:2014-09-24 14:55:00

标签: json swift

我正在使用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
}

如果两种方式都有效,那将会有所帮助。

2 个答案:

答案 0 :(得分:2)

{  "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信息。我像这样用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)
    }
}

答案 1 :(得分:1)

这是我用来循环你的JSON“代码”并得到(或打印)每个人姓名的解决方案......

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'
    }
}

这就是你应该需要的。我不打扰你尝试过的其他东西。我希望这会帮助你。