假设你的数据结构是
[
{
"data": [
"\u65b0\u5317\u5e02\u4e09\u91cd\u5340",
"\u65b0\u5317\u5e02\u6c38\u548c\u5340",
"\u53f0\u5317\u5e02\u4e2d\u5c71\u5340",
"\u53f0\u5317\u5e02\u4e2d\u6b63\u5340",
"\u53f0\u5317\u5e02\u4fe1\u7fa9\u5340",
"\u53f0\u5317\u5e02\u5357\u6e2f\u5340",
"\u53f0\u5317\u5e02\u5927\u540c\u5340",
"\u53f0\u5317\u5e02\u5927\u5b89\u5340",
"\u53f0\u5317\u5e02\u6587\u5c71\u5340",
"\u53f0\u5317\u5e02\u677e\u5c71\u5340",
"\u53f0\u5317\u5e02\u842c\u83ef\u5340"
]
}
]
将JSON转化为实体同时符合Codable Protocol
typealias DistEntity = [Dist]
struct Dist: Codable {
let data: [String]
}
实现模型层
protocol JSONFetcher: AnyObject {
func distParser(forResource fileName: String, completionHandler handler: @escaping((Result<DistEntity, Error>) -> ()))
}
class ModelLayer: JSONFetcher {
enum ParserError: Error {
case PathNotFound
case ConvertsObjectError
case DecoderError
}
func distParser(forResource fileName: String, completionHandler handler: @escaping((Result<DistEntity, Error>) -> ())) {
guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else { return handler(.failure(ParserError.PathNotFound)) }
guard let jsonData = try? Data(contentsOf: url) else { return handler(.failure(ParserError.ConvertsObjectError)) }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
guard let distEntity: DistEntity = try? decoder.decode(DistEntity.self, from: jsonData) else { return handler(.failure(ParserError.DecoderError)) }
handler(.success(distEntity))
}
}
业务逻辑层接口中的初步解析
final class viewModel {
private var fetcher: JSONFetcher
init(fetcher: JSONFetcher = ModelLayer()) {
self.fetcher = fetcher
}
private func distParser() {
self.fetcher.distParser(forResource: "YourJSONFileName") { (result) in
switch result {
case .success(let entity):
print("[Dist Entity]: \(entity)")
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
无法确保这对您的场景有用,
如果没有解决,能否提供更详细的信息。