如何快速遍历嵌套的json对象?

时间:2019-11-29 12:53:26

标签: arrays json swift api loops

我一直在尝试检索邮政编码 来自以下Google API,但无法遍历JSON数组

这是解析JSON的功能

func parseJson(Json:Data)  {

    let decoder = JSONDecoder()
    do {
        let decodedData = try decoder.decode(MapModel.self, from: Json)
        let postal_code = decodedData.results[0].address_components[0].long_name

        print(postal_code)

    } catch {                
        print(error)
        return   
    }             
}

这是模型:

struct MapModel: Decodable { 
    let results : [Result] 
    let status: String 
    let plus_code : compoundCode 
} 

struct compoundCode: Decodable { 
    let compound_code: String 
} 

struct Result: Decodable { 
    let address_components:[address_components] 
} 

struct address_components: Decodable { 
    let long_name : Int 
}

这是通过API的JSON

{  
   "plus_code":{  
      "compound_code":"5WXX+7J Thane, Maharashtra, India",
      "global_code":"7JFJ5WXX+7J"
   },
   "results":[  
      {  
         "address_components":[  
            {  
               "long_name":"400604",
               "short_name":"400604",
               "types":[  
                  "postal_code"
               ]
            },
            {  
               "long_name":"Thane",
               "short_name":"Thane",
               "types":[  
                  "administrative_area_level_2",
                  "political"
               ]
            }
         ]
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

我得到了以下问题的答案...问题是给定JSON对象的键“ long_name”有多个值。解决方案是遍历“ address_components”并查找JSON对象中“类型”键的唯一值。例如,在本例中,键“ long_name”具有两个值“ thane”和“ 400604”,但是唯一键是可用于区分那些< / p>

这是以下问题的语法!

func parseJson(Json:Data)  
      {

        let decoder = JSONDecoder()

        do{
            let decodedData = try decoder.decode(MapModel.self, from: Json)

            for item in decodedData.results[0].address_components{
                if item.types[0] == "postal_code"{
                    print(item.long_name)
                }
            }
        }

        catch{

            print(error)
            return 

        }
    }