我一直在努力争取这一天超过一天我不知道为什么当我在我的结构中明确定义键时,我一直得到Missing Key错误。非常感谢您的帮助。请帮助澄清我对如何在JSON中解码嵌套类型的困惑。
我正在尝试解析以下JSON响应,但在运行我的应用程序时不断收到Missing Key错误消息。以下是我从服务中收到的消息。
这是JSON共鸣
{
UserInfo = {
ApplicationArea = {
CreationDateTime = "2018-02-11 21:34:40.646000";
MfgCode = PSUN;
Sender = DM;
};
ServiceStatus = {
StatusCode = 0;
StatusDescription = Success;
System = "Product Info";
};
UserInfoDataArea = {
Email = "john@example.com";
Locale = "en_US";
UserId = 3;
UserName = jdoe;
};
};
}
这是错误
Missing Key: applicationArea
Debug description: No value associated with key applicationArea ("ApplicationArea").
下面是我获取请求和解码响应的结构代码。
struct UserInfo:Codable {
struct ApplicationArea:Codable {
let creationDateTime: String
let mfgCode: String
let sender: String
private enum CodingKeys: String, CodingKey {
case creationDateTime = "CreationDateTime"
case mfgCode = "MfgCode"
case sender = "Sender"
}
}
let applicationArea: ApplicationArea
enum CodingKeys: String, CodingKey {
case applicationArea = "ApplicationArea"
}
}
创建请求的代码
let apiMethod = HTTPMethod.post
Alamofire.request(
loginURL!,
method: apiMethod,
parameters: params,
encoding: URLEncoding.default,
headers: header)
.responseJSON { (response) -> Void in
switch response.result {
case .success:
print(response.result.value)
let result = response.data
do {
let decoder = JSONDecoder()
let userDetails = try decoder.decode(UserInfo.self, from: result!)
print("Response \(userDetails)")
} catch DecodingError.keyNotFound(let key, let context) {
print("Missing Key: \(key)")
print("Debug description: \(context.debugDescription)")
} catch {
print("Error \(error.localizedDescription)")
}
case .failure(let error):
print("Error \(error)")
}
}
答案 0 :(得分:1)
您犯了一个非常常见的错误:您忽略了根对象,即包含UserInfo
密钥的最外层字典。
创建Root
结构
struct Root: Decodable {
let userInfo : UserInfo
enum CodingKeys: String, CodingKey { case userInfo = "UserInfo" }
}
解码
let root = try decoder.decode(Root.self, from: result!)
let userDetails = root.userInfo