UTF8
您可以尝试将文件作为普通txt 文件读取。您将遍历行,将行分成由“ = ”分隔的组件,然后将结果放入某个字典中。然后将字典序列化为 JSON 数据。
可能类似于以下内容:
func parseLocalizationStringFilesToJSON(files: [(path: String, key: String)]) throws -> Data {
// Generate a dictionary that will be in the end parsed to JSON
var dictionary: [String: [String: String]] = [String: [String: String]]()
// Iterate through all files
try files.forEach { file in
// try reading file as UTF8 string
let fileString = try String(contentsOfFile: file.path, encoding: .utf8)
// Break down file string to lines
let lines = fileString.components(separatedBy: .newlines)
// Extract from each line
lines.forEach { line in
// TODO: Skip lines that do not start with "
let separator = " = " // A separator used to separate key-value in strings file
let lineComponents = line.components(separatedBy: separator) // Break down to components
if lineComponents.count >= 2 { // There may be more than 2 components. Imagine: localizationKey1 = "A = B";
// TODO: Trim the key to remove whitespaces and "
let key = lineComponents[0] // Key is always the first component
// TODO: Trim the value to remove whitespaces and "
let value = lineComponents[1...].joined(separator: separator) // The rest must be joined back together
var innerDictionary: [String: String] = dictionary[key] ?? [String: String]() // Extract current sub-json at this key or create a new sub-json
innerDictionary[file.key] = value // Assign a new value
dictionary[key] = innerDictionary // Put back to main dictionary
}
}
}
// Serialize it to JSON data
return try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
}
此方法未经测试,只是即时编写。它还有 3 点仍需要实施以删除所有额外的部分并忽略不相关的行。
用法如下:
let jsonData: Data = try? parseLocalizationStringFilesToJSON(files: [
(Bundle.main.path(forResource: "Localizable", ofType: "string(English)"), "en"),
(Bundle.main.path(forResource: "Localizable", ofType: "string(German)"), "de"),
(Bundle.main.path(forResource: "Localizable", ofType: "string(French)"), "fr")
])
我希望这至少能让你开始。我建议您在出现问题时询问其他更具体的问题,或者如果您无法找到仍有待完成的部分的答案。