How to use Swift's Codable Super personal memo

SwiftyJson is convenient, but Swift table standard function Codable was also reasonably easy to use, so note

An example of converting json to instance with the simplest Codable, which is not practical

Just make the struct inherit Codable, convert the data of json, and then use JSONDecoder.decode. However, the type information defined in Codable and the form of json must be exactly the same. Therefore, if even one json key is missing, an error will occur.


var data = """
{
  "name": "Bob",
  "age": 20,
  "sex": "male",
}
""".data(using: .utf8)!

struct User: Codable {
  let name: String
  let age: Int
}

let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: 1, age: 20)

Practical use of Codable (if json key is missing)

Change the class of struct as follows and initialize it in the init function. Written in pure swift, it's easy to understand.

var data = """
{
  "name": "Bob",
  "age": 20,
}
""".data(using: .utf8)!

class User: Codable {
  var name: String
  var age: Int
  var sex: String? //sex is not in json!

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? nil
        self.age = try container.decodeIfPresent(Int.self, forKey: .age) ?? nil
        self.sex = try container.decodeIfPresent(String.self, forKey: .sex) ?? nil
    }
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: "Bob", age: 20, sex: nil)

Summary

Codable isn't too bad compared to Swifty Json.

Recommended Posts

How to use Swift's Codable Super personal memo
How to use arrays (personal memorandum)
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
Note how to use Swift super basic TableView
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
[For super beginners] How to use autofocus: true
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
Understand how to use Swift's JSON Decoder in 3 minutes
How to use GitHub for super beginners (team development)
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use Java variables
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer
[Java] How to use Optional ①
How to use Lombok now
[Creating] How to use JUnit