Mansuu....
Mansuu....

Reputation: 1226

Parse JSON data in swift

I am trying to parse my json data in swift 3.0. I am using Alamofire 4.0+ Here is my json

{
"token": 

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

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

Here is my model class to hold these values

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

None of the solution available on internet worked for me. How can I parse this json and map to the model class? Any help here?

Upvotes: 0

Views: 324

Answers (2)

vadian
vadian

Reputation: 285079

I was mistaken, the value for key user is indeed a regular array.

This is a solution without a third party mapper and with an extra User struct (by the way the value for key expires is an Int rather than Double). Assuming the user data comes from a database which always sends all fields the user keys are forced unwrapped. If this is not the case use optional binding also for the user data:

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

Upvotes: 2

Fangming
Fangming

Reputation: 25261

Here is the answer with map replaced by dictionary. Don't forget to handle error or unwrap carefully :)

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

Upvotes: 0

Related Questions