如何使用解码器解码Swift 4中的这个json? 我希望能够获得"令牌"它本身就可以存储在Keychain中。
{
"success":true,
"token":"***"
,
"user": {
"id": "59f0ec6d5479390345980cc8",
"username": "john",
"email": "john@gmail.com"
}
}
我试过这个,但它没有打印任何东西。
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, _, _) in
guard let data = data else { return }
do {
let jsonwt = try JSONDecoder().decode(JWT.self, from: data)
print(jsonwt.token)
} catch {}
}
task.resume()
}
我可以把它放在捕获之后,但这会得到整个json,我不想要那个。
print(String(data: data, encoding: .utf8)!)
这是结构。我认为这就是问题所在。
struct User: Decodable {
let id: String
let username: String
let email: String
}
struct JWT: Decodable {
let success: String
let token: String
let user: User
}
答案 0 :(得分:1)
这是一些游戏代码,演示了在Swift中解析JSON的代码:
//: Playground - noun: a place where people can play
import UIKit
import XCTest
import PlaygroundSupport
let json = """
{
"success":true,
"token":"***"
,
"user": {
"id": "59f0ec6d5479390345980cc8",
"username": "john",
"email": "john@gmail.com"
}
}
""".data(using: .utf8)!
do {
if let data = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:Any], let token = data["token"] {
print("token is \(token)")
}
} catch _ {
print("Failed to decode JSON")
}
答案 1 :(得分:1)
像这样工作:
struct User : Codable
{ var id : String
}
struct JWT : Codable
{ var success : Bool
var token : String
var user :User
}
let json = """
{ \"success\" : true,
\"token\" : \"***\",
\"user\":
{ \"id\": \"59f0ec6d5479390345980cc8\",
\"username\": \"john\",
\"email\": \"john@gmail.com\"
}
}
"""
let decoder = JSONDecoder()
let jwt = try decoder.decode(JWT.self, from: json.data(using: .utf8)!)
print ("token: \(jwt.token)")