swift4
부터 추가된 프로토콜
json
을 간편하고 쉽게 인코딩 / 디코딩
할 수 있게 해준다.
Encoding
과 Decoding
은 protocol
이다.
Codable
을 사용해서 JSON
으로 인코딩하고 싶다면 반드시 Codable
이라는 프로토콜
을 준수하고 있어야 한다.struct Human : Codable {
var name : String
var age : Int
}
let Johnson : Human = .init(name : "Johnson", age : 39)
Johnson
이라는 구조체변수를 인코딩let data = try? JSONEncoder().encode(Johnson)
// {"name":"Johnson", "age" : "39"}
let data = """
{
"name" : "Johnson",
"age" : "39"
}
"""
서버에서 위와 같은 데이터를 받았다고 해보자.
이 데이터를 Human
구조체 변수에 Decoding하겠다.
let johnson = try? JSONDecoder().decode(Human.self, from : data)
그러면 파싱해서 잘 들어간다.
Decoding fail
로서 nil
이 들어간다.CodingKey
를 사용하여 Key의 이름이 바뀌었다는 걸 명시해서 이름을 바꿔줄 수 있다고 한다. struct Human : Codable{
var name : String
}
enum CodingKeys : String, CodingKey{
case name = "Name"
}
특정 Key-value 없이 오는 경우
를 들 수 있는데struct Human : Codable{
var name : String
}
let data =
"""
{
}
""".data(using : .utf8)!
let johnson = try? JSONDecoder().decode(Human.self, from : data)
nil
이다.때문에 이런 경우를 대비하여 2가지 처리를 할 수 있다.
Key
가 없을 경우를 대비하여 직접 Decoding
함수를 작성한다.init(from decoder : Decoder)
가 호출되는데 키가 없을 경우의 기본 값을 세팅해준다.enum CodingKeys : String, CodingKey{
case name = "Name"
}
struct Human : Codable{
var name : String
init(from decoder : Decoder) throws{
let values = try decoder.container(keyedBy : CodingKeys.self)
name = try? values.decode(String.self, forKey: .name) ?? ""
}
}
CodingKeys
의 name의 키 값에 맞는 컨테이너를 가져오는데 없다면 nil
이 반환된다.nil
이 반환되면 try?
에 따라서 해당 표현식 역시 nil
이 되고 이 경우에 옵셔널 값에 따라서 ""
가 문자열 name에 할당되게 된다. 변수
를 옵셔널
로 선언한다.struct Human : Codable{
var name : String?
}
으로 아예 처음부터 옵셔널로 선언하는 방법.
null
이 들어있는 채로 왔다.let data = try? JSONDecoder().decode(Human.self, from :data)
는 에러가 나서 try?
에 따라서 nil
을 반환한다.
이런 경우에는 아예 구조체를
struct Human : Codable{
var name : String?
}
옵셔널로 선언한다.