简体   繁体   中英

How to loop through nested json objects in swift?

I have been trying to retrieve Postal_code from the following google API but unable to loop through the JSON array

This is the function for parsing 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   
    }             
}

this is the model:

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 
}

This the JSON through API

{  
   "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"
               ]
            }
         ]
      }
   ]
}

I have got the answer for the following question...the problem was there multiple values for the key "long_name" for the give JSON objects..the solution for this is to loop through the "address_components" and look for the unique values for the "type" key in the JSON object..for Example in this case the key "long_name " had two values "thane" and "400604" but the unique key is the types that can be used to differentiate between those

This is the syntax for the folloing problem!!

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 

        }
    }

What do you mean with unable to loop through ?. What is the error? Is it at compile time or run time?. As far as I can imagine, it could be because of the long_name type, it is not an Int, it's a String.

And as a comment, try to use Apple coding conventions like camel case naming. And search for coding Keys to make your code more readable and attached to those conventions :

struct AddressComponents : Decodable {
       let longName : String

       enum codingKeys : String, CodingKey {
            case longName = "long_name"
       }
}

Try

for item in decodedData.results {
    for inner in item.address_components {
         print(inner.long_name)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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