diff --git a/README-CN.md b/README-CN.md index 16517592..95e3f021 100644 --- a/README-CN.md +++ b/README-CN.md @@ -306,6 +306,29 @@ func mapping(map: Map) { } ``` +# 支持多个Key +有些JSON相同意义的Value对应了多个不同的Key。例如: +第一个JSON: +```json +{ + "code" : 200, + "message" : "success" +} +``` +第二个JSON: +```json +{ + "code" : 200, + "msg" : "success" +} +``` +对于'success'的值, 你可以像这样来访问它: +```swift +func mapping(map: Map) { + identifier <- map["message|msg", nested: false, delimiter: "|"] +} +``` + # 自定义转换规则 ObjectMapper 也支持在映射时自定义转换规则。如果要使用自定义转换,创建一个 tuple(元祖)包含 ```map["field_name"]``` 和你要使用的变换放在 ```<-``` 的右边: diff --git a/README.md b/README.md index 2aacbd8e..b110198c 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,29 @@ func mapping(map: Map) { } ``` +# Support Multi-Keys +Different JSON use different keys to identify the values that mean same thing. Likes, +First JSON: +```json +{ + "code" : 200, + "message" : "success" +} +``` +Second JSON: +```json +{ + "code" : 200, + "msg" : "success" +} +``` +For the 'success' value, you can access the multi-keys object as follows: +```swift +func mapping(map: Map) { + identifier <- map["message|msg", nested: false, delimiter: "|"] +} +``` + # Custom Transforms ObjectMapper also supports custom transforms that convert values during the mapping process. To use a transform, simply create a tuple with `map["field_name"]` and the transform of your choice on the right side of the `<-` operator: ```swift diff --git a/Sources/Map.swift b/Sources/Map.swift index 1ca9903a..f5d04f12 100644 --- a/Sources/Map.swift +++ b/Sources/Map.swift @@ -106,7 +106,16 @@ public final class Map { // break down the components of the key that are separated by delimiter (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON) } else { - let object = JSON[key] + var object = JSON[key] + if object == nil && key.contains(delimiter) { + let components = key.components(separatedBy: delimiter) + for item in components { + object = JSON[item] + if object != nil { + break + } + } + } let isNSNull = object is NSNull isKeyPresent = isNSNull ? true : object != nil currentValue = isNSNull ? nil : object