Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

arrays - 如何快速遍历嵌套的json对象?(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

(我一直在尝试从以下Google API检索Postal_code,但是无法遍历JSON数组)

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

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

(通过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"
               ]
            }
         ]
      }
   ]
}
  ask by Rajat Kotian translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(据我所能想象的,可能是因为long_name类型,它不是Int,而是字符串。)

And as a comment, try to use Apple coding conventions like camel case naming.

(作为注释,请尝试使用Apple编码约定,例如驼峰式命名。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...