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

时间:2018-07-19 22:45:37

标签: json swift

有人可以看到我所缺少的吗?我无法解码过去的结果。结果下将不会打印任何内容。我查看了其他与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(结果)中打印任何字段,则值不会自动填充,并且会收到错误消息。我在解码中缺少什么吗?

1 个答案:

答案 0 :(得分:0)

您需要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,但是它具有数组结果,其中所有元素都包含该键