我是快速编程的新手,正在尝试从服务器获取JSON格式的用户数据,然后将其“粘贴”到结构中:
这是我的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)
}
});
});
这是JSON响应:
{
userID = (
{
email = test;
id = 1;
money = 200;
password = test;
username = test;
}
);
}
这是我的apiCall函数:
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)
}
})
}
这是我的结构:
struct user {
var id : String
var username : String
var password : String
var email : String
var money : String
}
我试图在MainPageViewController中创建一个数组,然后追加它,但是我不知道如何:
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.
}
答案 0 :(得分:2)
您可以尝试
struct Root: Codable {
let userID: [User]
}
struct User: Codable {
let email: String
let id, money: Int
let password, username: String
}
do {
let res = try JSONDecoder().decode(Root.self,from:data)
users = res.userID
}
catch {
print(error)
}
并将Alamofire从responseJSON
更改为responseData
Alamofire.request(url).responseData(completionHandler : { (response) in
switch response.result {
case .success( let data):
// I want to append the user struct by the user data collected from JSON
print(response.result.value!)
do {
let res = try JSONDecoder().decode(Root.self,from:data)
userData = res.userID
}
catch {
print(error)
}
case .failure(let error):
print (error)
}
})
答案 1 :(得分:2)
最好的方法是使用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)
编辑
要回答您的进一步问题,请像这样使用它:
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
}