如何将json响应存储到变量中?

时间:2019-05-24 12:01:50

标签: ios json swift

我从api获得json响应。我需要使用模型存储到变量中,如何存储?

struct StructLogin {
    var status:String?
    var contentarr = [content]()
}
struct content {
    var AuthoToken:String?
    var user_name:String?
    var user_type:String?
}

let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
StructLoginObj.status = jsonResponse!["status"] as? String
StructLoginObj.contentarr = contentArray

contentObj.AuthoToken = jsonResponse!["auth_token"] as? String
contentObj.user_name = jsonResponse!["user_name"] as? String
contentObj.user_type = jsonResponse!["user_type"] as? String
  

{“状态”:“ 200”,“内容”:{“ user_type”:“ 1”,“ user_name”:“超级管理员”,“ auth_token”:“ 7500b440c0f8035e864e1541c650b888”}}

3 个答案:

答案 0 :(得分:1)

使用 Codable 将您的JSON响应解析为一个对象。

struct Login: Codable {
    var status: String?
    var content:Content?

}
struct Content: Codable {
    var auth_token:String?
    var user_name:String?
    var user_type:String?
}

让我们以您提供的JSON响应为例。

let str = """
{"status":"200","content":{"user_type":"1","user_name":"Super Admin","auth_token":"7500b440c0f8035e864e1541c650b888"}}
"""

由于我们没有来自Data的实际API,因此我们将str转换为data进行解析。

if let data = str.data(using: .utf8) {
    let login = try? JSONDecoder().decode(Login.self, from: data)
    print(login)
}

答案 1 :(得分:1)

您需要使用Codable轻松将对象转换为数据,而且您的content键是字典而不是数组

保存:

let decoder = JSONDecoder() 
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try! decoder.decode(Root.self, from: data)  
print(res.content)
let data = try! JSONEncoder().encode(res.content)
// save data anywhere e.x userDefaults if it's a settings 

 UserDefaults.shared.set(data,forKey:"User")

阅读:

if let data = UserDefaults.shared.data(forKey:"User") {
  print(data)
}

struct Root: Codable {
    let status: String
    let content: Content
} 
struct Content: Codable {
    let userType, userName, authToken: String 
}

答案 2 :(得分:0)

您可以使用JSON.parse()方法将API的返回值转换为JavaScript对象:

let result = JSON.parse(data);