我已经使用JSONSerialization对此进行了解码。但是就我自己的知识和代码的维护而言。我想知道如何解码。
这是我到目前为止所拥有的:
let urlString = "site deleted" + "/DataSource/Mobile/?Action=MyProfile&uid=" + uid + "&uuid=" + uuid
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { (data, _, error) in
if let err = error {
print("Handle MyProfileJSON error: ", err)
}
guard let data = data else {return}
do {
// swift 4.2 but we cant use it right now
let profile = try JSONDecoder().decode(RequestResult.self, from: data)
print(profile)
completion(profile)
} catch let err {
print("Handle Decoder Error: ", err)
}
}.resume()
我不太担心这些案件,但这是我到目前为止的事情。我知道我使用的不是惯例,这就是为什么我使用JSONSerialization做到这一点,所以可以使用 camelCase 。如果您也可以帮助我将其转换为camelCase,那将是惊人的,但是我的重点是使用Decodable
类对此进行解码。非常感谢,伙计们。
这是我的结构:
struct RequestResult: Decodable {
var Action: String?
var Params: [String: String]?
var DATA: [String: String]?
}
struct Params: Decodable {
var Action_get: String?
var uid_get: String?
}
struct DATA: Decodable {
var Id: String?
var UserCode: String?
var HomePhone: String?
var Mobile: String?
var WorkPhone: String?
var Email: String?
var AltEmail: String?
var UnitNo: String?
var StreetNo: String?
var StreetName: String?
var City: String?
var StateProvince: String?
var Country: String?
var ZipPostalCode: String?
}
答案 0 :(得分:1)
JSON的结构非常清晰
RequestResult
包含一个字符串和两个字典。 CodingKeys
可用于将键重命名为更有意义且符合约定的名称。枚举案例的左侧是struct成员名称,右侧是原始JSON密钥。所有结构成员都可以声明为常量(let
,如果JSON始终包含密钥,则可以声明为非可选。
struct RequestResult: Decodable {
private enum CodingKeys : String, CodingKey {
case action = "Action", params = "Params", data = "DATA"
}
let action: String
let params: Parameter
let data: UserData
}
密钥Params
的字典将重命名为Parameter
,而DATA
则重命名为UserData
struct Parameter: Decodable {
private enum CodingKeys : String, CodingKey {
case action = "Action_get", uid = "uid_get"
}
let action: String
let get: String
}
struct UserData: Decodable {
private enum CodingKeys : String, CodingKey {
case id = "Id", userCode = "UserCode", homePhone = "HomePhone"
case mobile = "Mobile", workPhone = "WorkPhone", email = "Email"
case altEmail = "AltEmail", unitNo = "UnitNo", streetNo = "StreetNo"
case streetName = "StreetName", city = "City", stateProvince = "StateProvince"
case country = "Country", zipPostalCode = "ZipPostalCode"
}
let id: String, userCode, homePhone, mobile: String
let workPhone, email, altEmail, unitNo: String
let streetNo, streetName, city, stateProvince: String
let country, zipPostalCode: String
}