Frank's Book
  • Introduction
  • Privacy Policy
  • Git
    • [Git]Fully delete a git repository created with init
  • iOS
    • iOS Book
      • [iOS] Swift Coding Style
      • [iOS] UnitTest With XCode
      • [iOS] Build a Universal Framework for iOS using Swift
      • [iOS] Memory Management
      • [iOS] GCD And Operation Queue
      • [iOS] MVVM
      • [iOS] CoreData
      • [iOS] KVO & KVC
      • [iOS] Asynchronous Operation
      • [iOS] URLSession
      • [iOS] NSTimer & CADisplayLink
      • [iOS] UITextField & UITestView
      • [iOS] UITableView & UICollectionView
      • [iOS] Codable
      • [iOS] Array的sort, filter, map, reduce 函式
      • [iOS] Class vs Struct
      • [iOS] Reference Type vs Value Type
      • [iOS] Object
      • [iOS] IBDesignable & IBInspectable
  • Jenkins
    • Jenkins & Docker
      • [Docker] Docker Commands
      • [Docker] 1. Setup Jenkins with Docker on Mac
      • [Docker] 2. Jenkins建立Mac子節點
      • [Docker] 3. Mac節點build Xcode project設定
      • [Jenkins] 1. Install Jenkins
      • [Jenkins] 2. Change Default User Of Jenkins
      • [Jenkins] 3. Integration with Git
      • [Jenkins] 4. Integration with XCode
      • [Jenkins] 5. Integration with Unit Test
      • [Jenkins] 6. Uninstall Jenkins
      • [Jenkins] 7. Jenkins Commands
      • [Jenkins] 8. Jenkins Plugins
      • [Jenkins] 9. Problem Solving
  • Flutter
    • Flutter Book
      • [Flutter] Update your Flutter path (Mac OS)
      • [Flutter] Release Command
      • [Flutter] Life Cycles
      • [Flutter] AppLifecycleState
      • [Flutter] Navigator Pop時回傳資料
      • [Flutter] Install appium-flutter-driver
  • Leet Code
    • LeetCode Solutions
      • [LeetCode] 1. Two Sum [Easy]
      • [LeetCode] 2. Add Two Numbers [Medium]
      • [LeetCode] 3. Longest Substring Without Repeating Characters [Medium]
      • [LeetCode] 5. Longest Palindromic Substring [Medium]
      • [LeetCode] 7. Reverse Integer [Easy] [LeetCode]
      • [LeetCode] 8. String to Integer (atoi)
      • [LeetCode] 11. Container With Most Water
      • [LeetCode] 13. Roman to Integer
      • [LeetCode]14. Longest Common Prefix
      • [LeetCode] 15. 3Sum
      • [LeetCode] 17. Letter Combinations of a Phone Number
      • [LeetCode] 19. Remove Nth Node From End of List
      • [LeetCode] 20. Valid Parentheses
      • [LeetCode] 21. Merge Two Sorted Lists
      • [LeetCode] 22. Generate Parentheses
      • [LeetCode] 26. Remove Duplicates from Sorted Array
      • [LeetCode] 28. Implement strStr()
      • [LeetCode] 33. Search in Rotated Sorted Array
      • [LeetCode] 34. Find First and Last Position of Element in Sorted Array
      • [LeetCode]36. Valid Sudoku
      • [LeetCode] 38. Count and Say
      • [LeetCode] 46. Permutations
      • [LeetCode] 48. Rotate Image
      • [LeetCode] 49. Group Anagrams
  • Git
    • Git Commands
      • [LeetCode] 50. Pow(x, n)
  • About Author
    • Frank Chen
Powered by GitBook
On this page
  1. iOS
  2. iOS Book

[iOS] Codable

JSON是目前受到廣泛應用的資料形式, 但在Swift 4以前, 解析JSON到對象裡面並不是一件容易的事情, 有些人會特別寫framework或使用第3方framework來專門處理JSON資料的轉換. Swift 4之後, Codable的出現讓大家可以更輕鬆的處理JSON資料了.

這邊直接用code說明:

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()
    }
}
Previous[iOS] UITableView & UICollectionViewNext[iOS] Array的sort, filter, map, reduce 函式

Last updated 6 years ago