LoginSignup
23

More than 5 years have passed since last update.

Swift3でJSONパースを行う

Posted at

Swift3でJSONパースを行う

今回の目標

JSON文字列のパースを行います

色々と便利なライブラリ(SwiftyJson等)があるそうですが、今回はApple標準フレームワークのFoundationに含まれており特別な設定等なく使用できるJSONSerializationを使用してJSONパースを行ってみます。

開発環境

Xcode:8.2.1
言語:Swift 3
OS:MacOS

手順

  1. パースするJSONの形式を確認
  2. JSONパースする

1. パースするJSONの形式を確認

今回パースするJSONは下記を想定します

personalData.json
[
 {
  "id":"1",
  "content":{
    "name":"suzuki",
    "age":25}
 },
 {
  "id":"2",
  "content":{
    "name":"sato",
    "age":20}
 }
]

ここで形式を確認しておくのは、JSONを取り出す際に正しい型にキャストを行う必要があるためです。
今回はトップレベルが配列([])で、その下が辞書({})型になっています。

2. JSONパースする

JSONSerialization を使用してJSONパースを行なったあと、キャストを繰り返して値を取り出しています

jsonParseTest.swift
import Foundation

// JSONデータを作成
let jsonString: String = "[{\"id\":\"1\", \"content\": {\"name\":\"suzuki\",\"age\":25}},{\"id\":\"2\", \"content\": {\"name\":\"sato\",\"age\":20}}]"
var personalData: Data =  jsonString.data(using: String.Encoding.utf8)!

// ここから本題
do {
    let json = try JSONSerialization.jsonObject(with: personalData, options: JSONSerialization.ReadingOptions.allowFragments) // JSONパース。optionsは型推論可(".allowFragmets"等)
    let top = json as! NSArray // トップレベルが配列
    for roop in top {
        let next = roop as! NSDictionary
        print(next["id"] as! String) // 1, 2 が表示

        let content = next["content"] as! NSDictionary
        print(content["age"] as! Int) // 25, 20 が表示
    }
} catch {
    print(error) // パースに失敗したときにエラーを表示
}

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
23