美文网首页
swift 手动合并两个Json

swift 手动合并两个Json

作者: 大成小栈 | 来源:发表于2023-10-28 19:20 被阅读0次

swift 手动合并两个Json文件,至原来两个特定的字段theme_skin_color、theme_skin_image中:

    // 重新映射Json格式
    static func remapSkinConfigJson(version: String) {
        let configPath = self.getCommonSkinConfigPath(version: version)
        let configJson = self.getCommonSkinConfigJson(atPath: configPath)
        
        var remapJson = [String: Any]()
        var colorDict = [String: String]()
        var imageDict = [String: String]()
        
        self.traverseConfigJson(configJson: configJson, prefix: "", colorDict: &colorDict, imageDict: &imageDict)
        self.mergeOldThemeJson(colorDict: &colorDict, imageDict: &imageDict)
        remapJson["theme_skin_color"] = colorDict
        remapJson["theme_skin_image"] = imageDict
        
        let remapSkinConfigPath = self.getRemapSkinConfigPath(version: version)
        let jsonData = self.encodeDictToJsonData(remapJson)
        self.writeJsonDataToFile(jsonData, atPath: remapSkinConfigPath)
    }
    
    // 递归遍历Json中的所有字段
    static func traverseConfigJson(configJson: [String: Any], prefix: String, colorDict: inout [String: String], imageDict: inout [String: String]) {
        for (key, value) in configJson {
            var keyPrefix = prefix
            if keyPrefix.isEmpty {
                keyPrefix = key
            } else {
                keyPrefix = keyPrefix + "_" + key
            }
            
            if let valueStr = value as? String {
                if valueStr.hasPrefix("#") {
                    colorDict[keyPrefix] = valueStr
                } else {
                    imageDict[keyPrefix] = valueStr
                }
                
            }
            
            if let subDictionary = value as? [String: Any] {
                traverseConfigJson(configJson: subDictionary, prefix: keyPrefix, colorDict: &colorDict, imageDict: &imageDict)
            }
        }
    }
    
    // merge原来旧的字段
    static func mergeOldThemeJson(colorDict: inout [String: String], imageDict: inout [String: String]) {
        let themeWhiteJsonPath = Bundle.main.path(forResource: "theme_white", ofType: "json") ?? ""
        let themeWhiteJson: [String: Any] = self.readConfigFileData(atPath: themeWhiteJsonPath)
        
        if let colorFields = themeWhiteJson["theme_skin_color"] as? [String: String] {
            colorDict.merge(colorFields) { value1, value2 in
                return value1
            }
        }
        if let imageFields = themeWhiteJson["theme_skin_image"] as? [String: String] {
            imageDict.merge(imageFields) { value1, value2 in
                return value1
            }
        }
    }

相关文章

网友评论

      本文标题:swift 手动合并两个Json

      本文链接:https://www.haomeiwen.com/subject/ysjmidtx.html