简体   繁体   English

如何从 Swift4 中的嵌套字典访问值?

[英]How to access a value from a nested dictionary in Swift4?

I want to get the value of City: in my json structure.我想在我的 json 结构中获取City:的值。 I receive the data inside a Dictionary with dictionary: [String : Any]?我在带有字典的字典中接收数据:[String : Any]?

I already tried several methods but nothing worked for me.我已经尝试了几种方法,但没有任何方法对我有用。 I think my problem is because auf the nested structure with the multiple { and [我认为我的问题是因为 auf 具有多个 { 和 [

{
"Format": "XXXXXXXXX",
"FormatVersion": "1.0",
"Status": "OK",
"NumToReturn": 1,
"AllResults": [
{
  "ConversationState": {
    "ConversationStateTime": XXXXXXXXX,
    "QueryEntities": {
      "Where": [
        {
          "Type": "City",
          "Label": "Stuttgart, Germany",
          "SpokenLabel": "Stuttgart",
          "Address": "Stuttgart, Baden-Wurttemberg, Germany",
          "City": "Stuttgart",
          "Admin2": "Regierungsbezirk Stuttgart",
          "Admin1": "Baden-Wurttemberg",
          "Country": "Germany",
          "CountryCode": "DE",
          "IATA": "STR",
          "Geohash": "u0wt8bd9854n",
          "Verified": true,
          "HighConfidence": true,
          "CurrentLocation": false,
          "Latitude": 48.78231811523438,
          "Longitude": 9.177020072937012,
          "ReferenceDatum": "WGS84",
          "TimeZone": "Europe/Berlin",
          "Radius": 10,
          "Links": [
            {
              "Label": "Wikipedia",
              "URL": "http://en.wikipedia.org/wiki/Stuttgart"
            }
          ],
          "TypeID": 5,
          "SourceID": 2,
          "RecordID": 2825297
        }
      ]
    }
   }
  }
 ]
}
import Foundation

struct YourClass: Codable {
    let format, formatVersion, status: String
    let numToReturn: Int
    let allResults: [AllResult]

    enum CodingKeys: String, CodingKey {
        case format = "Format"
        case formatVersion = "FormatVersion"
        case status = "Status"
        case numToReturn = "NumToReturn"
        case allResults = "AllResults"
    }
}

struct AllResult: Codable {
    let conversationState: ConversationState

    enum CodingKeys: String, CodingKey {
        case conversationState = "ConversationState"
    }
}

struct ConversationState: Codable {
    let conversationStateTime: String
    let queryEntities: QueryEntities

    enum CodingKeys: String, CodingKey {
        case conversationStateTime = "ConversationStateTime"
        case queryEntities = "QueryEntities"
    }
}

struct QueryEntities: Codable {
    let queryEntitiesWhere: [Where]

    enum CodingKeys: String, CodingKey {
        case queryEntitiesWhere = "Where"
    }
}

struct Where: Codable {
    let type, label, spokenLabel, address: String
    let city, admin2, admin1, country: String
    let countryCode, iata, geohash: String
    let verified, highConfidence, currentLocation: Bool
    let latitude, longitude: Double
    let referenceDatum, timeZone: String
    let radius: Int
    let links: [Link]
    let typeID, sourceID, recordID: Int

    enum CodingKeys: String, CodingKey {
        case type = "Type"
        case label = "Label"
        case spokenLabel = "SpokenLabel"
        case address = "Address"
        case city = "City"
        case admin2 = "Admin2"
        case admin1 = "Admin1"
        case country = "Country"
        case countryCode = "CountryCode"
        case iata = "IATA"
        case geohash = "Geohash"
        case verified = "Verified"
        case highConfidence = "HighConfidence"
        case currentLocation = "CurrentLocation"
        case latitude = "Latitude"
        case longitude = "Longitude"
        case referenceDatum = "ReferenceDatum"
        case timeZone = "TimeZone"
        case radius = "Radius"
        case links = "Links"
        case typeID = "TypeID"
        case sourceID = "SourceID"
        case recordID = "RecordID"
    }
}

struct Link: Codable {
    let label: String
    let url: String

    enum CodingKeys: String, CodingKey {
        case label = "Label"
        case url = "URL"
    }
}

If your JSON is not example and you are using it, there is invalid JSON value in ConversationStateTime .如果您的JSON不是示例并且您正在使用它,则ConversationStateTime存在无效的 JSON 值。 Its value should be inside double quote unless it is an integer value.它的值应该在双引号内,除非它是一个整数值。

"ConversationStateTime": "XXXXXXXXX"

Hope this help!希望这有帮助!

  1. Please check your JSON.请检查您的 JSON。 "ConversationStateTime" doesn't have proper value “ConversationStateTime”没有正确的价值
  2. If its valid, please try this code to get "City" value from your JSON如果有效,请尝试使用此代码从您的 JSON 中获取“城市”值

    // response is your JSON func parseJSON() { let allResults = response!["AllResults"] as? NSArray for (_, element) in (allResults?.enumerated())! { let elementDict = element as? Dictionary<String, AnyObject> let conversationStateDict = elementDict!["ConversationState"] as? Dictionary<String, AnyObject> let queryDict = conversationStateDict!["QueryEntities"] as? Dictionary<String, AnyObject> let whereDict = queryDict!["Where"] as? NSArray for (_, whereDictElement) in (whereDict?.enumerated())! { let dict = whereDictElement as? Dictionary<String, AnyObject> print(dict!["City"]) } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM