[swift] ObjectMapper를 사용하여 JSON 데이터의 필드를 URI로 변환하는 방법은?
Swift에서 ObjectMapper를 사용하여 JSON 데이터의 필드를 URI로 변환하려면 ObjectMapper의 TransformType 프로토콜을 채택하여 변환 기능을 구현해야 합니다.
다음은 ObjectMapper를 사용하여 JSON 데이터의 필드를 URI로 변환하는 예시입니다.
- URITransform 클래스 생성하기
import ObjectMapper
class URITransform: TransformType {
typealias Object = URL
typealias JSON = String
init() {}
func transformFromJSON(_ value: Any?) -> Object? {
if let urlString = value as? String, let url = URL(string: urlString) {
return url
}
return nil
}
func transformToJSON(_ value: Object?) -> JSON? {
if let url = value {
return url.absoluteString
}
return nil
}
}
- 모델 클래스 생성하기
import ObjectMapper
class User: Mappable {
var id: Int?
var name: String?
var profileImageURL: URL?
required init?(map: Map) {}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
profileImageURL <- (map["profileImage"], URITransform())
}
}
위의 예시 코드에서는 URITransform
이라는 ObjectMapper의 TransformType 프로토콜을 구현한 클래스를 사용하였습니다.
User
클래스에서는 profileImageURL
필드를 profileImage
JSON 필드와 매핑하며, Transform으로 URITransform()
을 사용하여 JSON 데이터를 URL로 변환합니다.
이제 ObjectMapper를 사용하여 JSON 데이터를 매핑하면, profileImageURL
필드는 URI로 변환되어 저장됩니다.
참고 자료:
- ObjectMapper Github 페이지: https://github.com/Hearst-DD/ObjectMapper