LoginSignup
0
4

More than 5 years have passed since last update.

JsonをCodableを使ってパースする

Posted at

はじめに

今回はGoogleMapsAPIでジオコーディングした際に取得するjsonを参考にメモしていきます。

{
   "results":[
              {
     "formatted_address": "日本、〒160-0022 東京都新宿区新宿3丁目33−15−1F 新宿ペガサス館",
     "geometry":{
         "location":{
             "lat": 35.6908264,
             "lng": 139.7037312
         }
       },
     }
   ],
   "status": "OK"
}

Json

大きく分けて2つ、これを元に階層ごとにパースしていく。

[String:Any]

{・・・}

[Any]

[・・・]

Codable

今回は"formatted_address"と"location"の値を取得していく。そしてこんな感じの構造体。

ViewController.swift
struct GoogleMaps: Codable {
        let results: [Results]
    }
    struct Results: Codable {
        let formatted_address: String
        let geometry: Geometry
    }
    struct Geometry: Codable {
        let location: Location
    }
    struct Location: Codable {
        let lat: Double
        let lng: Double
    }

Decodeメソッド

取得したJsonDataのdecodeはこんな感じで

ViewController.swift
func decodeJson(data: Data) {
        do {
            let googleJson = try JSONDecoder().decode(GoogleMaps.self, from: data)
            let resultJson = googleJson.results[0]
            let address = resultJson.formatted_address
            let lat = resultJson.geometry.location.lat
            let lng = resultJson.geometry.location.lng
            print("address:\(address)_lat:\(lat)_lng:\(lng)"
        } catch {
            print("decodeJsonError!")
        }
    }

最後に

[Any:String]型でJsonがネストした時は({・・・})、Codable構造体変数は[]で囲まないことを忘れて少しハマりました。Jsonが[Any]型でネストした時に[]で配列宣言する。
終わり。

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4