SwiftUI 从 API 地理编码 google 获取 JSON 结果

SwitUI fetch JSON result from API geocode google

我必须从 geocode goodle API 中获取 JSON 结果。

JSON 结果:

{
  "plus_code" : {
  "compound_code" : "2V6X+23 Ostritz, Germania",
  "global_code" : "9F3P2V6X+23"
  },
  "results" : [
  {
     "address_components" : [
            {
              "long_name" : "Unnamed Road",
              "short_name" : "Unnamed Road",
              "types" : [ "route" ]
            },
            {
              "long_name" : "Ostritz",
              "short_name" : "Ostritz",
              "types" : [ "locality", "political" ]
            },
            {
              "long_name" : "Görlitz",
              "short_name" : "GR",
              "types" : [ "administrative_area_level_3", "political" ]
            },
            {
              "long_name" : "Dresden",
              "short_name" : "DD",
              "types" : [ "administrative_area_level_2", "political" ]
            }
     ],
     "formatted_address" : "Unnamed Road, 02899 Ostritz, Germania",
     "geometry" : {
            "bounds" : {
                  "northeast" : {
                    "lat" : 51.0103607,
                    "lng" : 14.898013
                    },
                  "southwest" : {
                    "lat" : 51.0093767,
                    "lng" : 14.8962029
                    }
             },
            "location" : {
                 "lat" : 51.0097477,
                 "lng" : 14.8972969
                 },
                 "location_type" : "GEOMETRIC_CENTER",
                 "viewport" : {
                    "northeast" : {
                        "lat" : 51.01121768029149,
                        "lng" : 14.8984569302915
                       },
                    "southwest" : {
                        "lat" : 51.0085197197085,
                        "lng" : 14.8957589697085
                       }
                   }
            },
           "place_id" : "ChIJ6egabgkhCUcRznhL6gAPj_w",
           "types" : [ "route" ]
     },
     {
     "address_components" : [
        {
           "long_name" : "Ostritz",
           "short_name" : "Ostritz",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Circondario di Görlitz",
           "short_name" : "GR",
           "types" : [ "administrative_area_level_3", "political" ]
        },
        {
           "long_name" : "Dresda",
           "short_name" : "DD",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Sassonia",
           "short_name" : "SN",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "Germania",
           "short_name" : "DE",
           "types" : [ "country", "political" ]
        }
     ],
     "formatted_address" : "Ostritz, Germania",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 51.06239919999999,
              "lng" : 14.964849
           },
           "southwest" : {
              "lat" : 50.9721983,
              "lng" : 14.87143
           }
        },
        "location" : {
           "lat" : 51.01573639999999,
           "lng" : 14.9314311
        },
        "location_type" : "APPROXIMATE",
        "viewport" : {
           "northeast" : {
              "lat" : 51.06239919999999,
              "lng" : 14.964849
           },
           "southwest" : {
              "lat" : 50.9721983,
              "lng" : 14.87143
           }
        }
     },
     "place_id" : "ChIJKfHi7N8gCUcR2V02pmCO3mU",
     "types" : [ "locality", "political" ]
  },
  ........ 
  ........
 ],
 "status" : "OK"
}

型号:

import Foundation

struct Postgeo: Codable {
   let plus_code: Plus_code
   let results: [Results]
   let status: String
}

struct Results: Codable {
   let address_components: [Address_components]
   let formatted_address: String
   let geometry: Geometry
   let place_id: String
   let plus_code: Plus_coderes
   let types: [String]
 }

 struct Geometry: Codable {
   let location: Location
   let location_type: String
   let viewport: Viewport
 }

 struct Plus_code: Codable {
   let compound_code, global_code: String
 }

 struct Address_components: Codable {
   let long_name, short_name: String
   let types: [String]
 }

 struct Location: Codable {
   let lat, lng: Double
 }

 struct Northeast: Codable {
   let lat, lng: Double
 }

API管理:

import Foundation
import Combine

class APIManager: ObservableObject {
   let objectWillChange = PassthroughSubject<Void, Never>()


   var postgeos = Postgeo.self {
      willSet {
          objectWillChange.send()
      }
   }

   init() {
      guard let url = URL(string: "<url>") else {
        fatalError("Invalid URL")
      }

      URLSession.shared.dataTask(with: url) { data, response, error in

          guard let json = data else { return }

          let postgeo = try? JSONDecoder().decode(Postgeo.self, from: json)

          print(postgeo)

          DispatchQueue.main.async {
              self.postgeos = postgeo
          }
          print("API values fetched Successfully")
      }.resume()
  }
}

调试时出现错误:

Cannot assign value of type 'Postgeo?' to type 'Postgeo.Type'

self.postgeos = postgeo

如果我评论这一行,我从 print(postgeo)

得到正确的结果

我已经为 swiftui 改编了一个 Json 获取代码,它可以很好地与以 '[' 开头的 Json 一起工作,但结果 json 来自 geocode google api 以'{'开头。

我该如何解决这个错误?

谢谢。

如果 print(postgeo) 显示正确结果,则 postgeos 导致问题。

您确实将 postgeos 声明为 Postgeo.self

删除 .self,添加 ? 并将 = 替换为 :

var postgeos : Postgeo? { ...