Swift如何解码ISO-8859-1(Latin1)字符串并迁移Java解压逻辑?
Swift 实现ISO-8859-1 URL解码 + Zlib解压逻辑
前置依赖
仅使用系统自带框架,无需第三方库,兼容版本:iOS 13.0+/macOS 10.15+/watchOS 6.0+/tvOS 13.0+
- 导入必要框架:
import Foundation import Compression
完整可运行代码
// MARK: Data Zlib解压扩展 extension Data { func zlibDecompressed() throws -> Data { guard !isEmpty else { return Data() } // 初始预估解压后大小为原始数据10倍,不足时自动扩容 return try zlibDecompressed(expectedSize: count * 10) } private func zlibDecompressed(expectedSize: Int) throws -> Data { var decompressedData = Data(count: expectedSize) let result = decompressedData.withUnsafeMutableBytes { destBuffer in self.withUnsafeBytes { srcBuffer in compression_decode_buffer( destBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self), destBuffer.count, srcBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self), srcBuffer.count, nil, COMPRESSION_ZLIB ) } } guard result > 0 else { throw NSError(domain: "ZlibError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Zlib解压失败,数据格式错误"]) } // 缓冲区足够容纳解压结果,裁剪多余空间 if result < expectedSize { decompressedData.count = result return decompressedData } // 缓冲区不足,扩大后重试 return try zlibDecompressed(expectedSize: expectedSize * 2) } } // MARK: 核心处理逻辑,对应Java的两步处理流程 func parseCompressedJson(encodedStr: String) throws -> Any { // 第一步:对应Java URLDecoder.decode(data, "ISO-8859-1") guard let urlDecodedStr = encodedStr.removingPercentEncoding, let compressedData = urlDecodedStr.data(using: .isoLatin1) else { throw NSError(domain: "DecodeError", code: -2, userInfo: [NSLocalizedDescriptionKey: "URL解码失败,编码格式不符"]) } // 第二步:Zlib解压 let rawData = try compressedData.zlibDecompressed() // 转换为JSON对象,支持字典/数组两种结构 return try JSONSerialization.jsonObject(with: rawData) }
调用示例
do { // 替换为你实际的原始编码字符串 let rawInput = "你的ISO-8859-1编码的原始数据源字符串" let jsonResult = try parseCompressedJson(encodedStr: rawInput) // 若已知JSON为字典结构,可直接转换 if let jsonDict = jsonResult as? [String: Any] { print("解析得到的JSON字典:\(jsonDict)") } // 若已知JSON为数组结构,可转换为数组 else if let jsonArray = jsonResult as? [Any] { print("解析得到的JSON数组:\(jsonArray)") } } catch { print("处理失败:\(error.localizedDescription)") }
逻辑对应说明
- Java端
URLDecoder.decode(data, "ISO-8859-1")对应Swift端encodedStr.removingPercentEncoding+ 转.isoLatin1编码的Data,两者逻辑完全对齐 - Java端Inflater解压对应Swift系统Compression框架的
compression_decode_buffer方法,使用COMPRESSION_ZLIB格式适配标准zlib压缩数据
内容的提问来源于stack exchange,提问作者dengST30
相关产品推荐
相关产品推荐

