Help us understand the problem. What is going on with this article?

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

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が最悪ですが、めげずに頑張りましょう。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away