【问题标题】:Type any has no subscript members swift 3键入任何没有下标成员的swift 3
【发布时间】:2016-09-30 13:02:03
【问题描述】:

我的代码是这样的

import UIKit
import Alamofire

class ViewController: UIViewController {


var young = "https://jsonplaceholder.typicode.com/posts"


override func viewDidLoad() {
    super.viewDidLoad()

    callAlamo(url: young)
}

func callAlamo(url: String){

    Alamofire.request(url).responseJSON { (response) in
        let responseJSON = response.data
        if responseJSON  == nil{
           print("response is empty")
        }else{
            print("Jon is \(responseJSON)")

            self.parseJson(JSONData: responseJSON!)
        }

    }
}

func parseJson(JSONData: Data){

    do{
        let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers)

        for  i in 0..<(readableJSON as AnyObject).count{
            print(readableJSON[i] as String)
        }

    }catch{
        print(error)
    }
}  
}

我需要这个 Json 中的每个数组元素。

【问题讨论】:

  • 关于同样的错误信息有 > 20 个问题。请检查您的问题是否之前没有得到解答。
  • 你能告诉我你正在获得表单服务的 JSON 吗?

标签: json swift swift3 alamofire


【解决方案1】:

尝试使用以下代码:

Alamofire.request(url).responseJSON { (response) in

        switch response.result {
        case .success(let value) :

            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value as! [String:AnyObject]!{
                print("JSON: ",JSON)
            }
        case .failure(let encodingError):
            completionHandler(APIResponse.init(status: "failure", response: nil, result:nil))
        }
    }

【讨论】:

    【解决方案2】:

    在使用responseJSON 处理程序时,JSON 数据已在内部由JSONSerialization 解析。您确实想再次尝试解析它,否则您将解析服务器的响应数据两次,这对性能非常不利。您需要做的就是:

    Alamofire.request(url).responseJSON { response in
        if let json = response.result.value {
            print("Parsed JSON: \(json)")
            // Now you can cast `json` to a Dictionary or Array
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多