LoginSignup
2
1

More than 5 years have passed since last update.

Swift 4 JSONをパースする方法

Last updated at Posted at 2018-06-15

はじめに

Swift4で、標準ライブラリのCodableプロトコルを使い、
JSONのパース処理を行った。

実装

  1. Stringのエクステンションを追加

    extension String {
        func decodeJSON<T>(_ type: T.Type) throws -> T where T : Decodable {
            return try JSONDecoder().decode(type, from: self.data(using: .utf8)!)
        }
    }
    
  2. エンティティを定義

    struct User : Codable {
        let name: String
    }
    
    struct Group : Codable {
        let users: [User]
    }
    
  3. 呼び出し元

    do {
        let user = try "{\"name\":\"佐藤\"}".decodeJSON(User.self)
        let users = try "[{\"name\":\"佐藤\"},{\"name\":\"鈴木\"}]".decodeJSON([User].self) // ←typeは配列型
        let group = try "{\"users\":[{\"name\":\"佐藤\"}]}".decodeJSON(Group.self)
    } catch {
        print("解析失敗")
    }
    
2
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
2
1