tristanhimmelman / ObjectMapper

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

hope support the "|" separator #1126

Open tospery opened 2 years ago

tospery commented 2 years ago

like, mutating func mapping(map: Map) { id <- map["areaId|serverId"] } when has not areaId, use serverId. can modify the follow code to support. private func subscript(key: String, nested: Bool? = nil, delimiter: String = ".", ignoreNil: Bool = false) -> Map { // save key and value associated to it currentKey = key keyIsNested = nested ?? key.contains(delimiter) nestedKeyDelimiter = delimiter

    if mappingType == .fromJSON {
        // check if a value exists for the current key
        // do this pre-check for performance reasons
        if keyIsNested {
            // break down the components of the key that are separated by delimiter
            (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON)
        } else {
            var object = JSON[key]

// add this code if object == nil && key.contains(delimiter) { let components = key.components(separatedBy: delimiter) for item in components { object = JSON[item] if object != nil { break } } } // end add

            var isNSNull = object is NSNull
            isKeyPresent = isNSNull ? true : object != nil
            currentValue = isNSNull ? nil : object
        }

        // update isKeyPresent if ignoreNil is true
        if ignoreNil && currentValue == nil {
            isKeyPresent = false
        }
    }

    return self
}