gpt4 book ai didi

json - 使用 swiftjson 遍历对象

转载 作者:搜寻专家 更新时间:2023-11-01 06:48:43 25 4
gpt4 key购买 nike

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

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

我正在尝试遍历 codes block 。到目前为止,我正在尝试:

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 片段。我像这样使用 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 - 使用 swiftjson 遍历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26020094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com