ios 在 Swift 中从 JSON 数组中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24074042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:34:42  来源:igfitidea点击:

Getting Values from JSON Array in Swift

iosswift

提问by DookieMan

I'm trying to retrieve values from an array that I get from a JSON web request. But I can't get the valueForKey function to work so I can apply the String to a label. The example below searches Apples API for software. As a test, I want to be able to apply the "trackName" key to a UILabel, but everything I try, I either crash, or return nil.

我正在尝试从从 JSON Web 请求获得的数组中检索值。但是我无法让 valueForKey 函数工作,所以我可以将字符串应用于标签。下面的示例在 Apples API 中搜索软件。作为测试,我希望能够将“trackName”键应用于 UILabel,但是我尝试的所有操作,要么崩溃,要么返回 nil。

Here is my code

这是我的代码

func searchFunction(searchQuery: NSString) {
    var url : NSURL = NSURL.URLWithString("https://itunes.apple.com/search?term=\(searchQuery)&media=software")
    var request: NSURLRequest = NSURLRequest(URL:url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        var newdata : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        var info : NSArray =  newdata.valueForKey("results") as NSArray

        var name: String? = info.valueForKey("trackName") as? String // Returns nil
        println(name)//Returns nil


        var name2 : NSString = info.valueForKey("trackName") as NSString //Crashes
        println(name2) //Crashes

        });


    task.resume()
    println("Resumed")

}

The comments next to the variables explains what happens with each one. Can someone explain how I can convert the valueForKey("trackName") to a string that can be applied to a label?

变量旁边的注释解释了每个变量会发生什么。有人可以解释我如何将 valueForKey("trackName") 转换为可以应用于标签的字符串吗?

Thank you!

谢谢!

回答by Midhun MP

Info is an array, so check with:

Info 是一个数组,因此请检查:

var name: String? = info[0].valueForKey("trackName") as? String
var name: String? = info[0].valueForKey("trackName") as? NSString