Swift - 驼峰与下划线JSON字符串(key)键名互转

扩展String方便转换获取Json数据时候的驼峰与下划线键名互转
extension String {
    
    private var camelName:String {
        var result = ""
        var flag = false
        self.forEach { c in
            let s = String(c)
            if s == "_" {
                flag = true
            } else {
                if flag {
                    result += s.uppercased()
                    flag = false
                } else {
                    result += s
                }
            }
        }
        return result
    }
    
    private var underscore_name:String {
        var result = ""
        self.forEach { c in
            let num = c.unicodeScalars.map { $0.value }.last!
            let s = String(c)
            if num > 64 && num < 91 {
                result += "_"
                result += s.lowercased()
            } else {
                result += s
            }
        }
        return result
    }
    
    enum JsonKeyType {
        case camel, underscore
    }
    
    func convertJsonKeyName(_ keyType: JsonKeyType) -> String {
        let pattern = "[\"' ]*[^:\"' ]*[\"' ]*:"
        var nsStr = self as NSString
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            // TODO: - 优化
            var res = regex.matches(in: nsStr as String, options:[NSRegularExpression.MatchingOptions(rawValue: 0)], range: NSMakeRange(0, (nsStr as NSString).length)) // 获取总位置数目
            for i in 0..
例子
    let cameljsonStr = """
    {
    "testData":[
    {
    "accountName":"Bill",
    "password":"12312312"
    },
    {
    "accountName":"George",
    "password":"123123"
    }
    ]
    }
    """
    print(cameljsonStr.convertJsonKeyName(.underscore))
    // res => underscorejsonStr

    let underscorejsonStr = """
    {
    "test_data":[
    {
    "account_name":"Bill",
    "password":"12312312"
    },
    {
    "account_name":"George",
    "password":"123123"
    }
    ]
    }
    """
    print(underscorejsonStr.convertJsonKeyName(.camel))
    // res => cameljsonStr

你可能感兴趣的:(Swift - 驼峰与下划线JSON字符串(key)键名互转)