LoginSignup
3
3

More than 1 year has passed since last update.

Swiftで簡単なJSONの取り扱い

Last updated at Posted at 2023-04-12

はじめに

JSONの取り扱いがよくわからなかったので簡単な操作をメモです

Data型

バイト列を表す 画像もJSONもバイト列によって表現できます

デコードとエンコード

エンコード 符号化

全角文字や制御文字を問題なく送信するために半角文字に置き換える技術
SwiftではJSONEncoderクラスがあるのでそれを使ってSwiftの値をJSONバイト列にエンコードします

デコード 復元化

エンコードから復元する技術
JSONDecoderクラスを使ってJSONバイト列をswiftの値にデコードします
サーバーからデータを受信する程で行うので今回はデコードを使います
https://developer.apple.com/documentation/foundation/jsondecoder/2895189-decode

Codableプロトコル

EncodableとDecodableを組み合わせたプロトコル

Decodableプロトコルのinit(from:)メソッドとEncodableプロトコルのencode(to:)メソッドを実装しなくてもコンパイラがコードの自動生成をするのでを実装しなくてもよい便利なプロトコルです。
https://qiita.com/s_emoto/items/deda5abcb0adc2217e86
https://developer.apple.com/documentation/swift/codable

サンプルコード

import Foundation

func sampleData() -> Data {
    return"""
{
    "id": 1,
    "name": "テストユーザ1",
    "mainText": "こんにちは"
}

""".data(using: .utf8)!
}

struct UserModel: Codable {
    var id: Int
    var name: String
    var mainText: String
}
func getJSON() {
    let jsonDecoder = JSONDecoder()
    // .decode(_:)メソッドに目的の型とデコード対象のData型の値を渡す
    guard let decodedUserModel = try? jsonDecoder.decode(UserModel.self, from: sampleData()) else {
        return
    }
    print(decodedUserModel)
}

getJSON()

ルートが配列の場合

import Foundation

func sampleData() -> Data {
    return"""
        [
            {
                    "id": 1,
                    "name": "テストユーザ1",
                    "mainText": "こんにちは"
            },
            {
                    "id": 2,
                    "name": "テストユーザ2",
                    "mainText": "こんばんは"
            }
        ]
        """.data(using: .utf8)!
}

struct UserModel: Codable {
    var id: Int
    var name: String
    var mainText: String
}
func getJSON() {
    let jsonDecoder = JSONDecoder()
    // [UserModel].selfにしてデコードする値の型を決めます
    guard let decodedUserModel = try? jsonDecoder.decode([UserModel].self, from: sampleData()) else {
        return
    }
    for model in decodedUserModel {
        print(model.id)
        print(model.name)
        print(model.mainText)
    }

}

getJSON()

ルートがオブジェクトで配列の場合

import Foundation

func sampleData() -> Data {
    return"""
        {
            "users": [
                {
                    "id": 1,
                    "name": "テストユーザ1",
                    "mainText": "こんにちは"
                },
                {
                    "id": 2,
                    "name": "テストユーザ2",
                    "mainText": "こんばんは"
                }
            ]
        }
        """.data(using: .utf8)!
}

struct UserModel: Codable {
    var id: Int
    var name: String
    var mainText: String
}
// [UserModel]型プロパティを持つCodableに準拠した構造体を作成
struct UserResponse: Codable {
    var users: [UserModel]
}
func getJSON() {
    let jsonDecoder = JSONDecoder()
    // デコードする値の型をUserResponseに設定
    guard let decodedUserModel = try? jsonDecoder.decode(UserResponse.self, from: sampleData()) else {
        return
    }
    print(decodedUserModel)
    for model in decodedUserModel.users {
        print(model.id)
        print(model.name)
        print(model.mainText)
    }
}
getJSON()

終わりに

簡単にJSONの取り扱いについてまとめました。
間違っていたら教えてください!

参考

https://programming-sansho.com/swift/how-to-codable/
[増補改訂第3版]Swift実践入門
https://gihyo.jp/book/2020/978-4-297-11213-4

3
3
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
3
3