ios从json urlsession dataTask获取可解码的对象参数

时间:2017-12-23 23:45:39

标签: ios json nsurlsessiondatatask urlsession decodable

从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。 我无法获得from:参数的正确格式我知道使用REST API和JSON并且可以真正使用帮助。谢谢

1 个答案:

答案 0 :(得分:0)

对于structmessage的对象,您需要type来包装此响应,例如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不需要在全局范围内,因为它只需要解析此特定请求。把它放在最适合你的应用程序的最窄范围内(可能只是在函数中。