36
36

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 5 years have passed since last update.

Swift4 CodableでJSONが扱いやすくなる?

Last updated at Posted at 2017-06-08

はじめに

Codableを利用するとJSONが扱いやすくなるようなので、
試してみました。

もうSwiftyJSONやObjectMapperなどのライブラリも不要になりそうです。

試してみる

1. JSONデータを用意する

テストデータ(JSON)
{
    "dateString":"2017-06-08 14:43:28 +0000",
    "weeks":[
             "sunny",
             "sunny",
             "cloudy",
             "cloudy",
             "cloudy",
             "rainy",
             "snowy"
        ]
}

2. 構造体を定義する

構造体にCodableを実装する

Forecast.swift
struct Forecast: Codable {

    enum WeatherType: String, Codable {
        case sunny, cloudy, rainy, snowy
    }

    var dateString = ""
    var weeks: [WeatherType]
}

3. JSONをパースする

decodeの第一引数にデータ型を指定すると、ドットでアクセスできるようになります。
簡単ですね。

デコードする

    if let path = Bundle.main.path(forResource: "forecast", ofType: "json") {

        let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path))

        let jsonDecoder = JSONDecoder()
        let forecast = try! jsonDecoder.decode(Forecast.self, from: jsonData)

        //ドットでアクセスできる
        print(forecast.dateString)

        _ = forecast.weeks.map {
            print($0)
        }
    }
出力結果
2017-06-08 14:43:28 +0000
sunny
sunny
cloudy
cloudy
cloudy
rainy
snowy

[おまけ] JSONのエンコードのサンプル

    let forecast = Forecast(dateString: Date().description,
                                weeks: [.sunny, .sunny, .cloudy, .rainy, .snowy])
    let jsonEncoder = JSONEncoder()
    let jsonData = try! jsonEncoder.encode(forecast)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print(jsonString ?? "unwap json")

    /// {"weeks":["sunny","sunny","cloudy","rainy","snowy"],"dateString":"2017-06-08 15:11:21 +0000"}
36
36
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
36
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?