[swift] ObjectMapper에서 사용되는 옵션들은 어떤 것이 있나요?

ObjectMapper는 JSON 데이터를 Swift 객체로 변환하는 라이브러리입니다. ObjectMapper를 사용하여 JSON을 파싱할 때 다양한 옵션을 사용할 수 있습니다.

  1. transformBlock: ObjectMapper는 JSON 데이터와 Swift 객체 간의 변환을 위해 transformBlock을 제공합니다. 이 옵션을 사용하면 특정 필드의 값을 변환할 수 있습니다. 예를 들어, 날짜 형식을 변환하거나 문자열을 숫자로 변환하는 등의 작업을 할 수 있습니다.
import ObjectMapper

class User: Mappable {
    var name: String?
    var age: Int?
    
    init() {}
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["name"]
        age <- (map["age"], transformBlock)
    }
    
    private let transformBlock: TransformOf<Int, String> = TransformOf<Int, String>(
        fromJSON: { (value: String?) -> Int? in
            return Int(value ?? "")
        },
        toJSON: { (value: Int?) -> String? in
            return String(value ?? 0)
        }
    )
}

let jsonString = "{\"name\": \"John\", \"age\": \"25\"}"
if let user = Mapper<User>().map(JSONString: jsonString) {
    print(user.name) // "John"
    print(user.age) // 25
}
  1. keyPath: ObjectMapper를 사용하면 JSON 데이터의 특정 keyPath에 있는 값만 파싱할 수도 있습니다. keyPath 옵션을 사용하면 필요한 데이터만 추출하여 객체에 매핑할 수 있습니다.
import ObjectMapper

class User: Mappable {
    var name: String?
    
    init() {}
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["user.name"]
    }
}

let jsonString = "{\"user\": {\"name\": \"John\"}}"
if let user = Mapper<User>().map(JSONString: jsonString) {
    print(user.name) // "John"
}
  1. ignoredProperties: ObjectMapper의 매핑에서 특정 프로퍼티를 무시하고 싶을 때 ignoredProperties 옵션을 사용할 수 있습니다. 이 옵션을 사용하면 JSON 데이터의 해당 키와 매핑되는 프로퍼티는 무시됩니다.
import ObjectMapper

class User: Mappable {
    var name: String?
    var age: Int?
    
    init() {}
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
    }
    
    var ignoredProperties: [String] {
        return ["age"]
    }
}

let jsonString = "{\"name\": \"John\", \"age\": 25}"
if let user = Mapper<User>().map(JSONString: jsonString) {
    print(user.name) // "John"
    print(user.age) // nil
}

ObjectMapper에서 사용 가능한 옵션들은 위에서 소개한 것들만이 아닙니다. 자세한 내용은 ObjectMapper GitHub 페이지를 참조하십시오.