在swift中解析JSON数据

时间:2017-07-05 13:04:55

标签: json swift alamofire objectmapper

我试图在swift 3.0中解析我的json数据。我正在使用Alamofire 4.0+ 这是我的json

{
"token": 

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

"user": 
[{"user_id":13,"user_first_name":"Himanshu","user_last_name":"Srivastava","full_name":"Himanshu Srivastava"}]
}

这是我的模型类来保存这些值

import Foundation
import ObjectMapper
class LoginResult:Mappable{
    var token:String?
    var expires:Double?
    var users:[[String:Any]]?
    required init?(map:Map){

    }

    func mapping(map:Map)->Void{
        self.token <- map["token"]
        self.expires <- map["expires"]
        self.users <- map["user"]
    }
}

互联网上提供的解决方案都不适合我。我如何解析这个json并映射到模型类? 这里有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

我错了,键user的值确实是一个常规数组。

这是一个没有第三方映射器和额外User结构的解决方案(按键expires的值为Int而不是Double)。 假设user数据来自始终发送所有字段的数据库,则强制解包用户密钥。如果不是这种情况,请对user数据使用可选绑定:

struct User {
    let firstName : String
    let lastName : String
    let fullName : String
    let userID : Int
}

class LoginResult {
    let token : String
    let expires : Int
    var users = [User]()

    init(json : [String:Any]) {
        self.token = json["token"] as? String ?? ""
        self.expires = json["expires"] as? Int ?? 0
        if let users = json["user"] as? [[String:Any]] {
            self.users = users.map { User(firstName: $0["user_first_name"] as! String,
                                          lastName: $0["user_last_name"] as! String,
                                          fullName: $0["full_name"] as! String,
                                          userID: $0["user_id"] as! Int)
            }
        }
    }
}

let json = "{\"token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\":504428378111,\"user\":[{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"    
let jsonData = json.data(using: .utf8)!    
do {
    if let userData = try JSONSerialization.jsonObject(with: jsonData) as? [String:Any] {
        let loginResult = LoginResult(json: userData)
        print(loginResult.users[0])
        // do something with loginResult
    }         
} catch {
    print(error)
}

答案 1 :(得分:0)

以下是用字典替换地图的答案。不要忘记处理错误或小心打开:)

let str = "{\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\": 1504428378111,\"user\": [{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]

    //Pass this json into the following function
}catch let error{

}

func mapping(json:[String: Any]?)->Void{
    self.token <- json?["token"] as? String
    self.expires <- json?["expires"] as? Double
    self.users <- json?["user"] as? [[String: Any]]
}