[swift] 38. 코더블(Codable)

RudinP·2023년 10월 5일
0

Study

목록 보기
56/227

(편의상 struct라 했지 당연히 class도 동일)

Codable

  • typealias Codable = Decodable & Encodable

Decodable

  • json -> struct

Encodable

  • struct -> json

CodingKeys

  • json에서 사용된 변수가 struct에서는 어떤 변수로 설정되는지 기입

예시

let jsonFromServer = """
{
	"nick_name" : "개발하는 정대리",
    "job": "유튜버, 개발자",
    "user_name":  "dev_jeongdaeri",
}
"""
// json -> struct: Decodable
struct User : Decodable{
//데이터는 옵셔널 처리를 해주어야 함
	var nickname: String?
    var job: String?
    var myUserName: String?
    
    enum CodingKeys: String, CodingKey{
    	case nickname = "nick_name"
        case job
        case myUserName = "user_name"
    }
    
    //Self == User
    static func getUserFromJson(_ jsonString: String) -> Self? {
    	guard let jsonData : Data = jsonString.data(using: .utf8) else{
        	return nil
    	}
        
        do {
        	let user = try JSONDecoder().decode(User.self, from: jsonData)
            return user
        } catch{
        	print("에러발생: \(error.localizedDescription)")
            return nil
    }
}
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글