Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON response to a struct in swift

I'm new in swift programming and am trying to get the user data in JSON format from the server and then "paste" it into a struct :

This is my api :

app.get('/getUser/:username',(req,res)=>{
    let user = req.params;
    var sql = "SELECT * FROM  users WHERE username = ? ";
    mysqlConnection.query(sql,[user.username],
    function(err, rows){
        if(!err){    

       res.send(JSON.stringify({"userID" : rows}));
}
 else {
console.log(err)
         }
    });
});

This is the JSON response:

{
    userID =     (
                {
            email = test;
            id = 1;
            money = 200;
            password = test;
            username = test;
        }
    );
}

This is my apiCall function :

    class func  getUser(username :String)
    {          
            let url = "http://127.0.0.1:3000/getUser/"+username
            Alamofire.request(url).responseJSON(completionHandler : { (response) in
                switch response.result {
                case .success( _):
                    // I want to append the user struct by the user data collected from JSON
                    print(response.result.value!)

                case .failure(let error):
                    print (error)
                }

            })                   
        }

And this My struct :

struct user {
    var id : String
    var username : String
    var password : String
    var email : String
    var money : String        
}

I Tried to create an array in my MainPageViewController and then append it but I don't know how :

class MainPageViewController: UIViewController {
    var currentUser : String?
    var userData = [user]()
    override func viewDidLoad() {
        API.getUser(username: currentUser!)
        print(currentUser!)

        super.viewDidLoad()
     //   API.getUserID(username: currentUser!)
        // Do any additional setup after loading the view.
    }
like image 886
louay baccary Avatar asked Feb 01 '26 13:02

louay baccary


1 Answers

Well best way to do would be with Codeable:

let data: YourJSONData

struct User: Codable {
    var id: String
    var username: String
    var password: String
    var email: String
    var money: String
}

let user = try? JSONDecoder().decode(User.self, from: data)

EDIT

To answer your further question, just use it like this:

static func getUserByUsername(_ username: String) {
    let url = "http://127.0.0.1:3000/getUser/" + username

    Alamofire.request(url).responseData(completionHandler : { (response) in
        switch response.result {
        case .success( let data):

            do {
                let user = try JSONDecoder().decode(Base.self, from: data)
            }
            catch {print(error)}

        case .failure(let error):
            print (error)
        }

    })
}

struct Base: Codable {
    let userID: [User]
}

struct User: Codable {
    var id: String
    var username: String
    var password: String
    var email: String
    var money: String
}
like image 172
Dennis Weidmann Avatar answered Feb 03 '26 04:02

Dennis Weidmann