gpt4 book ai didi

json - 解码 JSON Swift 4 - 嵌套对象/数组

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:10 25 4
gpt4 key购买 nike

任何人都可以看到我错过了什么吗?我无法解码过去的任何结果。结果下不会打印任何内容。我已经查看了其他几篇与 JSON/Swift 相关的帖子,但仍然不明白我做错了什么。这是我的 JSON:

{
"results": [
{
"user.ldap.principal": "OHWIL3336IPM101",
"common.os_version": "11.4",
"common.wifi_mac_address": "100caef1001d",
"common.status": "ACTIVE",
"common.creation_date": "2018-17-05T16:42:49.000Z",
"ios.iPhone UDID": "a8a7a2e52359353dfbacf026a4fada9ew1cb4c10",
"user.ldap.user_attributes.custom1": [
"3336"
],
"common.SerialNumber": "F9FWEF74GHMN",
"common.uuid": "01cd1ed3-b3af-48c0-8499-654c0a9ab996"
}
],
"totalCount": 1,
"resultCount": 1,
"searchTimeMillis": 1,
"currentServerTimeMilliseconds": 1531558334959,
"hasMore": false
}

这是我目前拥有的。

struct DeviceData: Codable {
let results: [Result]
let totalCount, resultCount, searchTimeMillis, currentServerTimeMilliseconds: Int
let hasMore: Bool
}

struct Result: Codable {
let commonOSVersion, commonStatus, commonImei, commonCreationDate: String?
let iosDeviceName, commonUUID, userLDAPPrincipal, commonWifiMACAddress: String?
let iosIPhoneUDID: String?
let userLDAPUserAttributesCustom1: [String]?
let commonSerialNumber: String?
let userLDAPGroupsName: [String]?
let iosIPhoneICCID: String?

enum CodingKeys: String, CodingKey {
case commonOSVersion = "common.os_version"
case commonStatus = "common.status"
case commonImei = "common.imei"
case commonCreationDate = "common.creation_date"
case iosDeviceName = "ios.DeviceName"
case commonUUID = "common.uuid"
case userLDAPPrincipal = "user.ldap.principal"
case commonWifiMACAddress = "common.wifi_mac_address"
case iosIPhoneUDID = "ios.iPhone UDID"
case userLDAPUserAttributesCustom1 = "user.ldap.user_attributes.custom1"
case commonSerialNumber = "common.SerialNumber"
case userLDAPGroupsName = "user.ldap.groups.name"
case iosIPhoneICCID = "ios.iPhone ICCID"
}
}

尝试解码:

   let decoder = JSONDecoder()
guard let data = data else {return}
do {
let json = try decoder.decode(DeviceData.self, from: data)
dump(json)
print(json.commonImei) //Does not print - Does not auto-populate - Error Here
}
catch let jsonError {
print("JSON Failed to Decode: ", jsonError)
}

错误:

 Value of type 'DeviceData' has no member 'commonImei'

json 将完整打印到控制台,但如果我尝试打印 Result (results) 中的任何字段,值不会自动填充,我会收到错误消息。我在解码时遗漏了什么吗?

最佳答案

你需要do-catch

do {
let decoder = JSONDecoder()
let json = try decoder.decode(DeviceData.self, from: data)
dump(json)
print(json.results[0].commonImei)
}
catch {
print(error)
}

//

json 表示结构 DeviceData 的对象,它不直接包含 commonImei,但它有一个数组结果,其中所有元素都包含该键

关于json - 解码 JSON Swift 4 - 嵌套对象/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51432689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com