# Swift Codable

* [**用Codable協議實現快速JSON解析**](https://swiftcafe.io/post/codable)

```swift
import Foundation

let jsonString = """
{
    "title": "Blah",
    "age": 12,
    "gender": "F",
    "body":{
        "weight": 60,
        "height": 180
    }
}
"""

struct Gender
{
    var sex: String!
}

struct Person: Codable
{
    // 一般配對
    var name: String!
    var age: Int!

    // JsonString->Object 一層變兩層
    var gender: Gender! = Gender()

    // JsonString->Object 兩層變一層
    var weight: Int!
    var height: Int!

    enum CodingKeys: String, CodingKey
    {
        case name = "title"
        case age

        case gender

        case body
    }

    enum BodyKeys: String, CodingKey
    {
        case weight
        case height
    }

    init(from decoder: Decoder) throws
    {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        age = try container.decode(Int.self, forKey: .age)

        gender.sex = try container.decode(String.self, forKey: .gender)

        let body = try container.nestedContainer(keyedBy: BodyKeys.self, forKey: .body)
        weight = try body.decode(Int.self, forKey: .weight)
        height = try body.decode(Int.self, forKey: .height)
    }

    func encode(to encoder: Encoder) throws
    {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(age, forKey: .age)

        try container.encode(gender.sex, forKey: .gender)

        var body = container.nestedContainer(keyedBy: BodyKeys.self, forKey: .body)
        try body.encode(weight, forKey: .weight)
        try body.encode(height, forKey: .height)
    }
}
```

* 結果

![](https://1934061725-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4XrCDvjc3xNfiB-3eT%2F-M4Y-TstkTXMD9Y8W9l7%2F-M4Y03b7yxyBSAE_Qhmw%2FCodableResult.png?alt=media\&token=3abfa503-9829-4d69-948c-e559ff6e93b9)
