how do I parse Any in dictionary using swift

前端 未结 1 1918
北海茫月
北海茫月 2021-01-25 10:20

I\'m not how do it parse a dictionary value which is of type . I\'m able to read the key which is string and value is type of Any and has below sample values for gi

相关标签:
1条回答
  • 2021-01-25 11:03

    Do not use Any. Do not use NSArray. Do not use NSDictionary. This is Swift! Use Swift types and Swift decoding of the JSON.

    Here is your JSON as a Data object:

    [
        {
         "name":"Estonia",
         "topLevelDomain":[".ee"],
         "alpha2Code":"EE",
         "alpha3Code":"EST",
         "callingCodes":["372"],
         "capital":"Tallinn",
         "altSpellings":["EE","Eesti","Republic of Estonia","Eesti Vabariik"],
         "region":"Europe",
         "subregion":"Northern Europe",
         "population":1315944,
         "latlng":[59.0,26.0],
         "demonym":"Estonian",
         "area":45227.0,
         "gini":36.0,
         "timezones":["UTC+02:00"],
         "borders":["LVA","RUS"],
         "nativeName":"Eesti",
         "numericCode":"233",
         "currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],
         "languages":[
             {
              "iso639_1":"et",
              "iso639_2":"est",
              "name":"Estonian",
              "nativeName":"eesti"
             }
         ],
         "translations":
          {
           "de":"Estland",
           "es":"Estonia",
           "fr":"Estonie",
           "ja":"エストニア",
           "it":"Estonia",
           "br":"Estônia",
           "pt":"Estónia",
           "nl":"Estland",
           "hr":"Estonija",
           "fa":"استونی"
         },
         "flag":"https://restcountries.eu/data/est.svg",
         "regionalBlocs":[
           {
            "acronym":"EU",
            "name":"European Union",
            "otherAcronyms":[],
            "otherNames":[]
           }
         ],
         "cioc":"EST"
        }
    ]
    """
    let data = json.data(using: .utf8)!
    

    Here is how to extract the language name from it:

    struct Language : Decodable {
        let name : String
    }
    struct Entry : Decodable {
        let languages : [Language]
    }
    let entries = try! JSONDecoder().decode([Entry].self, from: data)
    let lang = entries[0].languages[0].name // Estonian
    
    0 讨论(0)
提交回复
热议问题