Skip to content

Support Multi-Keys #1129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"]``` 和你要使用的变换放在 ```<-``` 的右边:

Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion Sources/Map.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down