从urlsession dataTask的此响应中,我如何转换收到的数据:
response: {"message":"login successful","data":{"id":15,"username":"Dummy2","password":"1234","email":"Dummy2@gmail.com","createdAt":"2017-12-23T19:52:49.547Z","updatedAt":"2017-12-23T19:52:49.547Z"}}
使用语句
到此结构struct User : Codable{
var id: String
var username: String
var password: String
var email: String
var createdAt: String
var updatedAt: String
}
let user = try decoder.decode(User.self, from: jsonData)
它是类型数据的,但我只需要一个数据表,而不是两者,也不能为收到的jsondata下注。我无法获得合适的格式:im知道使用REST API和JSON,并且可以真正使用帮助。谢谢
您需要使用message
和type
对象的struct
来包装此响应,例如ResponseObject
:
struct User: Codable {
let id: Int // NB: You must use `Int` not `String`
let username: String
let password: String
let email: String
let createdAt: Date // NB: I'd use `Date`, not `String`
let updatedAt: Date
}
func parserUser(from data: Data) -> User? {
struct ResponseObject: Decodable {
let message: String
let data: User?
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
formatter.locale = Locale(identifier: "en_US_POSIX")
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let responseObject = try? decoder.decode(ResponseObject.self, from: data)
return responseObject?.user
}
let user = parseUser(from: data)
注意,此ResponseObject
不是需要在全局范围内的,因为仅需解析此特定请求即可。将其放在最狭窄的范围中,最适合您的应用程序(可能只是在功能中。