I have a JSON string value how to get the key value from the json using swift code?
{
"user":{ "id":"74d93200-2ed2-437c-976f-83710eaea923","firstName":"dev","lastName":"che", "username":"dev_che"}}
From this how to get the "username" value using swift code?
first define User struct
struct UserModel: Codable {
let user: User?
}
struct User: Codable {
let id, firstName, lastName, username: String?
}
then decode your model from json
let userData =
"{\"user\":{\"id\":\"74d93200-2ed2-437c-976f-83710eaea923\",\"firstName\":\"dev\",\"lastName\":\"che\", \"username\":\"dev_che\"}}"
let data = userData.data(using: .utf8)!
let userModel = try? JSONDecoder().decode(UserModel.self, from: data)
then you can use it this way :
userModel.username
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.