如何在Swift 4中使用Alamofire 4.7解析JSON

时间:2018-03-27 07:35:06

标签: ios json swift alamofire decode

我知道之前曾问过这个问题,但答案是在Swift 3中使用旧版本的Alamofire。

问题:无法弄清楚如何从JSON响应中检索数据,主要是 api_key

以下是我的回复代码:

Alamofire.request(serverLink!, headers: headers).responseJSON{ response in

        if response.value != nil {
            //Some code to get api_key
            print(response)
        } else {
            print("error")
        }

当我print(response)时,我得到以下内容:

        SUCCESS: {
    user =     {
        "api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370;
        "created_on" = "2010-09-30T12:57:42Z";
        firstname = Paul;
        id = 4;
        "last_login_on" = "2018-03-27T10:15:10+03:00";
        lastname = Smith;
        login = admin;
        mail = "admin@demo.com";
        status = 1;
    }; 
}

我需要得到的是

  

" API_KEY" = 9a13f31770b80767a57d753961acbd3a18eb1370;

它可以是数组,字典或只包含以下字符串的形式:

  

... 9a13f31770b807

有人可以向我解释如何从此请求获取(解码)它吗?

修改

print(response.result.value):

RESPONSE: Optional({ user = { "api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370; "created_on" = "2010-09-30T12:57:42Z"; firstname = Paul; id = 4; "last_login_on" = "2018-03-27T11:10:25+03:00"; lastname = Smith; login = admin; mail = "admin@demo.com"; status = 1; }; })

2 个答案:

答案 0 :(得分:3)

根据docs,这是您访问序列化JSON响应的方式:

if let json = response.result.value as? [String: Any] {
    print("JSON: \(json)") // serialized json response
}

要访问api_key,您只需先打开成功和用户词典,然后就可以访问用户词典中的api_key属性。

guard let user = json["user"] as? [String: Any],
      let apiKey = user["api_key"] as? String else {

      print("Failed to parse JSON")
      return
}

print(apiKey)

答案 1 :(得分:-2)

当你得到答案时,你可以。使用MapperObjectMapper类。

创建模型类

import Foundation
import ObjectMapper

public final class LoginModel: Mappable, NSCoding {

// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let status = "status"
static let login = "login"
static let firstname = "firstname"
static let id = "id"
static let lastname = "lastname"
static let mail = "mail"
static let apiKey = "api_key"
static let createdOn = "created_on"
static let lastLoginOn = "last_login_on"
}

  // MARK: Properties
 public var status: Int?
public var login: String?
public var firstname: String?
public var id: Int?
public var lastname: String?
public var mail: String?
public var apiKey: String?
public var createdOn: String?
public var lastLoginOn: String?

// MARK: ObjectMapper Initializers
/// Map a JSON object to this class using ObjectMapper.
///
 /// - parameter map: A mapping from ObjectMapper.
 public required init?(map: Map){

}

/// Map a JSON object to this class using ObjectMapper.
///
/// - parameter map: A mapping from ObjectMapper.
  public func mapping(map: Map) {
  status <- map[SerializationKeys.status]
  login <- map[SerializationKeys.login]
  firstname <- map[SerializationKeys.firstname]
  id <- map[SerializationKeys.id]
 lastname <- map[SerializationKeys.lastname]
 mail <- map[SerializationKeys.mail]
 apiKey <- map[SerializationKeys.apiKey]
 createdOn <- map[SerializationKeys.createdOn]
 lastLoginOn <- map[SerializationKeys.lastLoginOn]
}

/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
 public func dictionaryRepresentation() -> [String: Any] {
 var dictionary: [String: Any] = [:]
 if let value = status { dictionary[SerializationKeys.status] = value }
  if let value = login { dictionary[SerializationKeys.login] = value }
  if let value = firstname { dictionary[SerializationKeys.firstname] = value }
  if let value = id { dictionary[SerializationKeys.id] = value }
  if let value = lastname { dictionary[SerializationKeys.lastname] = value }
  if let value = mail { dictionary[SerializationKeys.mail] = value }
  if let value = apiKey { dictionary[SerializationKeys.apiKey] = value }
  if let value = createdOn { dictionary[SerializationKeys.createdOn] = value }
  if let value = lastLoginOn { dictionary[SerializationKeys.lastLoginOn] = value }
  return dictionary
 }

// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
  self.status = aDecoder.decodeObject(forKey: SerializationKeys.status) as? Int
  self.login = aDecoder.decodeObject(forKey: SerializationKeys.login) as? String
  self.firstname = aDecoder.decodeObject(forKey: SerializationKeys.firstname) as? String
  self.id = aDecoder.decodeObject(forKey: SerializationKeys.id) as? Int
  self.lastname = aDecoder.decodeObject(forKey: SerializationKeys.lastname) as? String
  self.mail = aDecoder.decodeObject(forKey: SerializationKeys.mail) as? String
  self.apiKey = aDecoder.decodeObject(forKey: SerializationKeys.apiKey) as? String
  self.createdOn = aDecoder.decodeObject(forKey: SerializationKeys.createdOn) as? String
  self.lastLoginOn = aDecoder.decodeObject(forKey: SerializationKeys.lastLoginOn) as? String
 }

public func encode(with aCoder: NSCoder) {
  aCoder.encode(status, forKey: SerializationKeys.status)
 aCoder.encode(login, forKey: SerializationKeys.login)
 aCoder.encode(firstname, forKey: SerializationKeys.firstname)
 aCoder.encode(id, forKey: SerializationKeys.id)
 aCoder.encode(lastname, forKey: SerializationKeys.lastname)
 aCoder.encode(mail, forKey: SerializationKeys.mail)
 aCoder.encode(apiKey, forKey: SerializationKeys.apiKey)
 aCoder.encode(createdOn, forKey: SerializationKeys.createdOn)
  aCoder.encode(lastLoginOn, forKey: SerializationKeys.lastLoginOn)
}

}

使用此模型类来映射您的回复......

Alamofire.request(serverLink!, headers: headers).responseJSON{ response in

    if let responseData = Mapper< LoginModel>().map(JSONObject: response.result.value)  {

          print(responseData.apiKey)

      } else {
         print("Fail to map data")  
      }

}