16
11

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でJSONをパースする

Last updated at Posted at 2017-10-18

文字列を、JSONオブジェクト(配列とディクショナリの組み合わせ)に変換します。

import Foundation

let str = """
    [{"name":"John","age":37},{"name":"Tim"}]
    """

struct ParseError: Error {}
func parse(json: String) throws {
    guard let data = json.data(using: .utf8) else {
         throw ParseError()
     }
    let json = try JSONSerialization.jsonObject(with: data)
    guard let rows = json as? [[String:Any]] else {
        throw ParseError()
    }
    for row in rows {
        let name = row["name"] ?? ""
        let age = row["age"] ?? 0
        print("\(name) is \(age)")
    }
}

do {
    try parse(json: str)
} catch {
    print("error")
}

参考: https://developer.apple.com/swift/blog/?id=37

16
11
2

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
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?