如何在Swift中解析Alamofire API的JSON响应?

Dev*_*per 117 json ios swift alamofire

以下代码我写了,我也在JSON中得到响应,但JSON的类型是"AnyObject",我无法将其转换为Array,以便我可以使用它.

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, JSON, error) in

    println(JSON?)
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*hty 152

Swift 2.0 Alamofire 3.0的答案应该看起来更像这样:

Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseJSON
{ response in switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")

                    let response = JSON as! NSDictionary

                    //example if there is an id
                    let userId = response.objectForKey("id")!

                case .Failure(let error):
                    print("Request failed with error: \(error)")
                }
    }
Run Code Online (Sandbox Code Playgroud)

https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md

Alamofire 4.0和Swift 3.0的更新:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
            .responseJSON { response in
                print(response)
//to get status code
                if let status = response.response?.statusCode {
                    switch(status){
                    case 201:
                        print("example success")
                    default:
                        print("error with response status: \(status)")
                    }
                }
//to get JSON return value
            if let result = response.result.value {
                let JSON = result as! NSDictionary
                print(JSON)
            }

        }
Run Code Online (Sandbox Code Playgroud)

  • 你如何得到JSON的实际内容?这是什么类型的对象?设计和文档是如此模糊,我无法弄清楚,在互联网上找不到任何例子...... (11认同)

Vik*_*ote 27

如上所述,您可以使用SwiftyJSON库并获取您的值,就像我在下面所做的那样

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, data, error) in

var json = JSON(data: data!)

       println(json)   
       println(json["productList"][1])                 

}
Run Code Online (Sandbox Code Playgroud)

我的json产品列表从脚本返回

{ "productList" :[

{"productName" : "PIZZA","id" : "1","productRate" : "120.00","productDescription" : "PIZZA AT 120Rs","productImage" : "uploads\/pizza.jpeg"},

{"productName" : "BURGER","id" : "2","productRate" : "100.00","productDescription" : "BURGER AT Rs 100","productImage" : "uploads/Burgers.jpg"}    
  ]
}
Run Code Online (Sandbox Code Playgroud)

输出:

{
  "productName" : "BURGER",
  "id" : "2",
  "productRate" : "100.00",
  "productDescription" : "BURGER AT Rs 100",
  "productImage" : "uploads/Burgers.jpg"
}
Run Code Online (Sandbox Code Playgroud)

  • 多德.有什么错误?提出单独的问题并提供一些细节.SwiftyJSON和魔术一样漂亮.尽可能使用它. (2认同)

小智 24

我在GitHub上找到了Swift2的答案

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 嗯我仍然失败构建了一条错误消息:'(_,_,_) - > Void'不能转换为'Response <AnyObject,NSError> - > Void' (5认同)
  • 这是Swift 2.0 + Alamofire JSON解析的正确版本. (3认同)

ilj*_*ljn 19

Swift 3,Alamofire 4.4和SwiftyJSON:

Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["people"][0]["name"].string
        if name != nil {
          print(name!)
        }
      }
  }
Run Code Online (Sandbox Code Playgroud)

这将解析此JSON输入:

{
  people: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*enL 17

我既不是JSON专家也不是Swift专家,但以下内容对我有用.:)我从我当前的应用程序中提取了代码,并且只更改了"MyLog to println",并用空格缩进以使其显示为代码块(希望我没有破坏它).

func getServerCourseVersion(){

    Alamofire.request(.GET,"\(PUBLIC_URL)/vtcver.php")
        .responseJSON { (_,_, JSON, _) in
          if let jsonResult = JSON as? Array<Dictionary<String,String>> {
            let courseName = jsonResult[0]["courseName"]
            let courseVersion = jsonResult[0]["courseVersion"]
            let courseZipFile = jsonResult[0]["courseZipFile"]

            println("JSON:    courseName: \(courseName)")
            println("JSON: courseVersion: \(courseVersion)")
            println("JSON: courseZipFile: \(courseZipFile)")

          }
      }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

编辑:

作为参考,这是我的PHP脚本返回的内容:

[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}]
Run Code Online (Sandbox Code Playgroud)


Saz*_*han 16

斯威夫特 5

class User: Decodable {

    var name: String
    var email: String
    var token: String

    enum CodingKeys: String, CodingKey {
        case name
        case email
        case token
    }

    public required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.email = try container.decode(String.self, forKey: .email)
        self.token = try container.decode(String.self, forKey: .token)
    }
}
Run Code Online (Sandbox Code Playgroud)

阿拉莫菲尔 API

    Alamofire.request("url.endpoint/path", method: .get, parameters: params, encoding: URLEncoding.queryString, headers: nil)
     .validate()
     .responseJSON { response in

        switch (response.result) {

            case .success( _):

            do {
                let users = try JSONDecoder().decode([User].self, from: response.data!)
                print(users)

            } catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }

             case .failure(let error):
                print("Request error: \(error.localizedDescription)")
         }
Run Code Online (Sandbox Code Playgroud)


Gia*_*ang 10

迅捷3

pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'

File json format:
{
    "codeAd": {
        "dateExpire": "2017/12/11",
        "codeRemoveAd":"1231243134"
        }
}

import Alamofire
import SwiftyJSON
    private func downloadJson() {
        Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
            debugPrint(response)

            if let json = response.data {
                let data = JSON(data: json)
                print("data\(data["codeAd"]["dateExpire"])")
                print("data\(data["codeAd"]["codeRemoveAd"])")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


iGh*_*ost 5

这是使用 Xcode 10.1 和 Swift 4 构建的

“Alamofire”(4.8.1)和“SwiftyJSON”(4.2.0)的完美结合。首先,您应该安装两个 Pod

pod 'Alamofire'pod 'SwiftyJSON'

JSON 格式的服务器响应:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", 
    "Accept-Language": "en;q=1.0", 
    "Host": "httpbin.org", 
    "User-Agent": "AlamoFire TEST/1.0 (com.ighost.AlamoFire-TEST; build:1; iOS 12.1.0) Alamofire/4.8.1"
  }, 
  "origin": "200.55.140.181, 200.55.140.181", 
  "url": "https://httpbin.org/get"
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想打印“主机”信息:“主机”:“httpbin.org”

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
        switch response.result {
        case .success:
            print("Validation Successful)")

            if let json = response.data {
                do{
                    let data = try JSON(data: json)
                    let str = data["headers"]["Host"]
                    print("DATA PARSED: \(str)")
                }
                catch{
                print("JSON Error")
                }

            }
        case .failure(let error):
            print(error)
        }
    }
Run Code Online (Sandbox Code Playgroud)

保持冷静和快乐代码