0

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?

11
  • 1
    It seems that the value for key user is another nested JSON string representing an array. If you are responsible for the server side change the format of the data and send a real array. Commented Jul 5, 2017 at 13:09
  • 3
    Your json is not correctly formatted. You can have an array under users, but why is that inside a double quote? Commented Jul 5, 2017 at 13:09
  • you need to convert data to json or what?? Commented Jul 5, 2017 at 13:10
  • Probably unrelated to your problem but I recommend defining an User: Mappable to represent user objects and in your LoginResult: Mappable I would declare users as var users: [User]? Commented Jul 5, 2017 at 13:14
  • @vadian I can't change the format because same format is being used in Android and web Commented Jul 5, 2017 at 13:15

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.