tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.13k stars 1.03k forks source link

Alternative keys for the same property #1101

Open xiaolinghuEr opened 4 years ago

xiaolinghuEr commented 4 years ago

Your JSON dictionary:

{
  "name": "ObjectMapper",
}
{
"userName" : "John Doe"
}

Your model:

class User :  Mappable{

    var userName : String?

    func mapping(map: Map) {
        userName <- map["userName"]
    }
}

What you expected:

Is there any way to let ObjectMapper support multiple keys for the same property in the Model ? Because the server APIs of different teams may return different fields to represent the same property in App. So there is a strong demand to support this scene. YYModel of Objective-C also support this function.

func mapping(map: Map) {
    userName <- map["userName", "user_name"]
}
gcharita commented 4 years ago

@xiaolinghuEr you can work your way around this by using something like this in your implementation of mapping(map:) function:

func mapping(map: Map) {
    userName <- map["userName"]
    if userName == nil {
        userName <- map["user_name"]
    }
}