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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26114831/
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 02:55:25  来源:igfitidea点击:

How to parse JSON response from Alamofire API in Swift?

iosjsonswiftalamofire

提问by Developer

Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.

按照我编写的代码,我也收到了 JSON 响应,但 JSON 的类型是“AnyObject”,我无法将其转换为 Array 以便我可以使用它。

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

    println(JSON?)
}

回答by Joseph Geraghty

The answer for Swift 2.0 Alamofire 3.0 should actually look more like this:

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)")
                }
    }

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

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

UPDATE for Alamofire 4.0 and Swift 3.0 :

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)
            }

        }

回答by Vikram Pote

like above mention you can use SwiftyJSON library and get your values like i have done below

如上所述,您可以使用 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])                 

}

my json product list return from script

我的 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"}    
  ]
}

output :

输出 :

{
  "productName" : "BURGER",
  "id" : "2",
  "productRate" : "100.00",
  "productDescription" : "BURGER AT Rs 100",
  "productImage" : "uploads/Burgers.jpg"
}

回答by mick80234

I found the answer on GitHub for Swift2

我在 GitHub 上找到了Swift2的答案

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

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)!)")
            }
        }
    }

回答by iljn

Swift 3, Alamofire 4.4, and SwiftyJSON:

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!)
        }
      }
  }

That will parse this JSON input:

这将解析此 JSON 输入:

{
  people: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}

回答by KenL

I'm neither a JSON expert nor a Swift expert, but the following is working for me. :) I have extracted the code from my current app, and only changed "MyLog to println", and indented with spaces to get it to show as a code block (hopefully I didn't break it).

我既不是 JSON 专家也不是 Swift 专家,但以下内容对我有用。:) 我已经从我当前的应用程序中提取了代码,只将“MyLog 改为 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)")

          }
      }
}

Hope this helps.

希望这可以帮助。

Edit:

编辑:

For reference, here is what my PHP Script returns:

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

[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}]

回答by Giang

swift 3

迅捷 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"])")
            }
        }
    }

回答by Carl Smith

I found a way to convert the response.result.value (inside an Alamofire responseJSON closure) into JSON format that I use in my app.

我找到了一种将 response.result.value(在 Alamofire responseJSON 闭包内)转换为我在我的应用程序中使用的 JSON 格式的方法。

I'm using Alamofire 3 and Swift 2.2.

我正在使用 Alamofire 3 和 Swift 2.2。

Here's the code I used:

这是我使用的代码:

    Alamofire.request(.POST, requestString,
                      parameters: parameters,
                      encoding: .JSON,
                      headers: headers).validate(statusCode: 200..<303)
                                       .validate(contentType: ["application/json"])
                                       .responseJSON { (response) in
        NSLog("response = \(response)")

        switch response.result {
        case .Success:
            guard let resultValue = response.result.value else {
                NSLog("Result value in response is nil")
                completionHandler(response: nil)
                return
            }

            let responseJSON = JSON(resultValue)

            // I do any processing this function needs to do with the JSON here

            // Here I call a completionHandler I wrote for the success case
        break
        case .Failure(let error):
            NSLog("Error result: \(error)")
            // Here I call a completionHandler I wrote for the failure case
            return
        }

回答by Luthfi Rahman

I usually use Glosslibrary to serialize or deserialize JSON in iOS. For example, I have JSON that looks like this:

我通常使用Gloss库在 iOS 中序列化或反序列化 JSON。例如,我有如下所示的 JSON:

{"ABDC":[{"AB":"qwerty","CD":"uiop"}],[{"AB":"12334","CD":"asdf"}]}

First, I model the JSON array in Gloss struct:

首先,我在 Gloss 结构中对 JSON 数组进行建模:

Struct Struct_Name: Decodable {
   let IJ: String?
   let KL: String?
   init?(json: JSON){
       self.IJ = "AB" <~~ json
       self.KL = "CD" <~~ json
   }
}

And then in Alamofire responseJSON, I do this following thing:

然后在 Alamofire responseJSON 中,我执行以下操作:

Alamofire.request(url, method: .get, paramters: parametersURL).validate(contentType: ["application/json"]).responseJSON{ response in
 switch response.result{
   case .success (let data):
    guard let value = data as? JSON,
       let eventsArrayJSON = value["ABDC"] as? [JSON]
    else { fatalError() }
    let struct_name = [Struct_Name].from(jsonArray: eventsArrayJSON)//the JSON deserialization is done here, after this line you can do anything with your JSON
    for i in 0 ..< Int((struct_name?.count)!) {
       print((struct_name?[i].IJ!)!)
       print((struct_name?[i].KL!)!)
    }
    break

   case .failure(let error):
    print("Error: \(error)")
    break
 }
}

The output from the code above:

上面代码的输出:

qwerty
uiop
1234
asdf

回答by Sazzad Hissain Khan

Swift 5

斯威夫特 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)
    }
}

Alamofire API

阿拉莫菲尔 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)")
         }

回答by iGhost

This was build with Xcode 10.1 and Swift 4

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

Perfect combination "Alamofire"(4.8.1) and "SwiftyJSON"(4.2.0). First you should install both pods

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

pod 'Alamofire'and pod 'SwiftyJSON'

pod 'Alamofire'pod 'SwiftyJSON'

The server response in JSON format:

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"
}

In this case I want print the "Host" info : "Host": "httpbin.org"

在这种情况下,我想打印“主机”信息:“主机”:“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)
        }
    }

Keep Calm and happy Code

保持冷静和快乐代码