简体   繁体   English

如何快速从 JSON 字符串中获取键值

[英]How to get the key value from the String of JSON in swift

I have a JSON string value how to get the key value from the json using swift code?我有一个 JSON 字符串值,如何使用 swift 代码从 json 中获取键值?

{ 
 "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?从这里如何使用swift代码获取“用户名”值?

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然后从 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM