0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftでJSONを読む

Posted at

今更感ありますが……

DecodableとJSONDecodeでJSONを読む

今回はこういうJSONを用意しました
JSONの元ネタ

currency.json
[
  {
    "alphabeticCode": "AED",
    "numericCode": 784
  },
  {
    "alphabeticCode": "AFN",
    "numericCode": 971
  },
  {
    "alphabeticCode": "ALL",
    "numericCode": 8
  }
]

Decodableプロトコルを継承した構造体を作ります
今回はJSONのキーとメンバ変数の名前を揃えます

struct Currency: Decodable{
    let alphabeticCode: String
    let numericCode: Int
}

JSONをData型で開きます
(ここではplaygroundのResourceフォルダに置いています)

let path = Bundle.main.path(forResource: "currency", ofType: "json")
let url = URL(fileURLWithPath: path!)
let currencyJson = try Data(contentsOf: url)

JSONDecoderで読みます
この時、[Currency]ではなくCurrencyで読みに行くとエラーになります(元のJSONもそういう構造になっていますね)

let result = try JSONDecoder().decode([Currency].self, from: currencyJson)
result.forEach { currency in
// ...
}

コード全文

import Foundation

struct Currency: Decodable{
    let alphabeticCode: String
    let numericCode: Int
}

let path = Bundle.main.path(forResource: "currency", ofType: "json")
let url = URL(fileURLWithPath: path!)
let currencyJson = try Data(contentsOf: url)
let result = try JSONDecoder().decode([Currency].self, from: currencyJson)
result.forEach { currency in
// ...
}

ありがとうございました

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?