gpt4 book ai didi

swift - 快速将 JSON 响应转换为结构

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:06 26 4
gpt4 key购买 nike

我是快速编程的新手,我正在尝试从服务器获取 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.
}

最佳答案

最好的方法是使用 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
}

关于swift - 快速将 JSON 响应转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53932841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com