【Swift】 JSONEncoder / JSONDecorder の基本的な使い方

Apple 公式リファレンスから。サンプルも抜粋。


func encode<T>(_ value: T) throws -> Data where T : Encodable


func decode<T>(
    _ type: T.Type,
    from data: Data
) throws -> T where T : Decodable

👉 encode(_:) | Apple Developer Documentation hatena-bookmark
👉 decode(_:from:) | Apple Developer Documentation hatena-bookmark


struct GroceryProduct: Codable {
  var name: String
  var points: Int
  var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/*
{
  "name" : "Pear",
  "points" : 250,
  "description" : "A ripe pear."
}
*/


struct GroceryProduct: Codable {
  var name: String
  var points: Int
  var description: String?
}

let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)

print(product.name) 

// Prints "Durian"

👉 JSONEncoder | Apple Developer Documentation hatena-bookmark
👉 JSONDecoder | Apple Developer Documentation hatena-bookmark

Codable というのは、Encodable + Decodable のこと。


typealias Codable = Decodable & Encodable

👉 Codable | Apple Developer Documentation hatena-bookmark

 

🧑🏻‍💻 まとめ

まとめると以下のイメージ。

Data と String の相互変換は以下。


さらに、キー名のカスタムをしたい場合は以下から。

👉 Encoding and Decoding Custom Types | Apple Developer Documentation hatena-bookmark



関連ワード:  appleiOSiPhonemacmacOSSwift今さら聞けない初心者開発