앱 개발자 역량/IOS
swift ] Codable
it_블로거
2019. 5. 13. 11:10
1. 개요
- Swift 4.0부터 Codable을 제공하게 되는 데 이는
"JSON과 같은 외부 표현과의 호환성을 위해 데이터 유형을 인코딩 및 디코딩 가능하게 만듭니다." 이런 정의를 가진다.
1) 기본 구조
struct Landmark: Codable {
var name: String
var foundingYear: Int
}
2) 직렬화 가능
- 다른 Codable 객체를 포함할 수 있다.
struct Landmark: Codable {
var name: String
var foundingYear: Int
var location: Coordinate
// Landmark is still codable after adding these properties.
var vantagePoints: [Coordinate]
var metadata: [String: String]
var website: URL?
}
3) Codable, Encodable, Decodable
- 둘다, 인코딩만, 디코딩만 용으로 사용할 수 있다.
struct Landmark: Encodable {
var name: String
var foundingYear: Int
}
struct Landmark: Decodable {
var name: String
var foundingYear: Int
}
struct Landmark: Encodable {
var name: String
var foundingYear: Int
}
struct Landmark: Decodable {
var name: String
var foundingYear: Int
}
2. 실전
- Alamorfire와 연동하기
1) 객체 확인
- NSDictionay 형태가 JSON 형태이므로 확인한다.
- 단 Array형태로 가져오기 때문에 [NSDictionary] 인지 확인한다.
if let _ = obj as? [NSDictionary]
2) JSON 형태로 디코딩
- 파일 클래스와, 데이터를 넣어준다.
let data = try JSONDecoder().decode([StoreInfo].self, from: jsonObj)
- 단 위와 같이하면 오류가 일어난다.
- obj가 NSDictionary형태는 맞지만 json데이터 포맷은 아니기 때문이다
- 아래와 같이 obj를 JSON으로 만들어준다.
let jsonObj = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
let data = try JSONDecoder().decode([StoreInfo].self, from: jsonObj)
3) 전체 코드
Alamofire.request(url, method: .post, parameters: param)
.responseJSON {(response) in
switch response.result
{
case .success(let obj):
print("succss1")
if let _ = obj as? [NSDictionary]
{
do
{
let jsonObj = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
let decoder = JSONDecoder()
let data = try decoder.decode([StoreInfo].self, from: jsonObj)
print(data[0].name)
print(data[0].addr)
print(data[0].recommend)
}
catch
{
print("fail")
print(error.localizedDescription)
}
}
break
case .failure(let error):
print("fail")
print(error.localizedDescription)
break
}
//print(response)
}
}