如何仅提取标题和艺术家?

时间:2015-12-07 06:03:10

标签: json swift parsing

我正在尝试提取所有标题和艺术家。我现在可以获得包含所有条目的JSON页面,但无法仅提取标题和艺术家。下面是访问该页面的代码。

enter image description here

 func getMeta(){

    let searchTerm = PFUser.currentUser?.username
    var endpoint = NSURL(string: "http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=\(searchTerm)&api_key=aa03f5bd00409f3bb5372c6ad0bc5655&format=json&callback=?")
    var data = NSData(contentsOfURL: endpoint!)

    let task = NSURLSession.sharedSession().dataTaskWithURL(endpoint!) {(data, response, error) -> Void in
        do {
            if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
            {
              if let items = dict["track"] as? NSArray {
                    for item in items {
                        let x =  (dict["track"]!["name"] as? String)!
                        print(x)
                    }
                }

            }

        } catch let jsonError as NSError {
        }
    }
    task.resume()
}

2 个答案:

答案 0 :(得分:1)

您永远不应忽略错误消息。

private class DownloadEReport extends AsyncTask<String, Void, Void> { int progress = 0; protected void onPreExecute() { mProgressDialog = new ProgressDialog(EReport.this); mProgressDialog.setTitle("Downloads"); mProgressDialog.setMessage("Downloading, Please Wait!"); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); mProgressDialog.setProgress(progress); } @Override protected Void doInBackground(String... strings) { String mUrl = strings[0]; String json = ""; int count; try { URL url = new URL(mUrl); URLConnection conection = url.openConnection(); conection.connect(); // getting file length int lenghtOfFile = conection.getContentLength(); // input stream to read file - with 8k buffer InputStream input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file OutputStream output = new FileOutputStream("/sdcard/downloadedfile.txt"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // writing data to file output.write(data, 0, count); // publishing the progress.... // After this onProgressUpdate will be called Log.e("JSON Download Progress", "" + (int) ((total * 100) / lenghtOfFile)); progress = (int) (total * 100 / lenghtOfFile); publishProgress(); } // flushing output output.flush(); // closing streams output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mProgressDialog.dismiss(); } } 分支内添加print(jsonError),您将看到错误:您的JSON无效。

为什么呢?因为在您的网址中,您使用catch在JSON字符串前面添加了JavaScript字符。

从网址中删除callback,网址应以&callback=?结尾。

然后你必须正确地遵循JSON类型:什么是字典,什么是数组,什么是键......并使用&format=json或任何其他已知方法安全地解包值:

if let

答案 1 :(得分:-1)

你为什么不试试Alamofire?

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }