> For the complete documentation index, see [llms.txt](https://frost.gitbook.io/iosbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://frost.gitbook.io/iosbook/ios/ios-book/ios-codable.md).

# \[iOS] Codable

這邊直接用code說明:

```swift
class ViewController: UIViewController {
    
    //定義json資料
    let jsonString = """   
    {
        "name": "Frank",
        "age":  "1",
        "adress2": null
    }
    """.data(using: .utf8)!
    
    //對應的struct
    struct Student: Codable { 
        let name: String
        let age: Int?  //注意這邊型態為Int, 
        let adress: String? //若參數可能為null或空值, 需設為optional, 否則轉換會失敗
        
        //自定義struct的properity與json的Key值相對應, 可省略
        enum CodingKeys: String, CodingKey {  
            case name
            case age
            case adress = "adress2"
        }
        
        //自己處理每個properity的轉換, 可省略. 
        //這邊是因為age的形態為Int, 但json對應到的值為String的"1", 無法直接轉換
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            let name = try? container.decode(String.self, forKey: .name)
            let age = try? container.decode(String.self, forKey: .age) 
            let ageInt = (age != nil) ? Int(age!) : 0  //轉換String to Int
            let adress = try? container.decode(String.self, forKey: .adress)

            self.init(name: name, age: ageInt, adress: adress)
        }
        
        init(name: String?, age: Int?, adress:String?) {
            self.name = name ?? ""
            self.age = age
            self.adress = adress ?? ""
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let student = try? JSONDecoder().decode(Student.self, from: self.jsonString) else {
            print("Error: Couldn't decode data into Student")
            return
        }
        
        print(student)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://frost.gitbook.io/iosbook/ios/ios-book/ios-codable.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
