LoginSignup
4
2

More than 3 years have passed since last update.

Swift 5 で読み込んだJSONを利用する

Last updated at Posted at 2019-10-05

JSONDecoderを利用するまでの方法はたくさん掲載されているが、それらを利用する方法が載っていなかったので。

なぜこの記事を書いたか

JSONを読み込むまでは良かったが、それを変数に代入した後、取り出すことができなかった。

具体的には下記エラーが発生したため。

# ***はアクセスしたいメンバー変数
Value of type 'Codable' (aka 'Decodable & Encodable') has no member '***'

方法

やり方は簡単で、JSONDecoder.decodeを受け取る変数に型を指定してあげるだけです。

なおhello.jsonはプロジェクト直下に置くこととします。

hello.json
{
  "hello":"world"
}
HelloEntity.swift
struct HelloEntity {
  var hello: String
}
decode.swift
func getFileData(_ filePath: String) -> Data? {
  let fileData: Data?
  do {
    let fileUrl = URL(fileURLWithPath: filePath)
    fileData = try Data(contentsOf: fileUrl)
  } catch {
    // ファイルデータの取得でエラーの場合
    fileData = nil
  }
  return fileData
}

func getJSON() {
  // forResource には拡張子を入れてはいけません
  let path = Bundle.main.path(forResource: "hello", ofType:"json")
  let data = getFileData(path)

  do {
    // ここの as! *** が重要
    let json = try! JSONDecoder().decode(HelloEntity.self, from: data!) as! HelloEntity

    print(json.hello)
    // => "world"
  }
}

XcodeVSCodeIntelli Jを使っているユーザーから見るとUI/UXが最悪ですが、めげずに頑張りましょう。

4
2
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
4
2