如何解决SwiftyJSON将字符串数组转换为数组不起作用
我的数据如下:
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"
]
但是当我想将其转换为数组时,我使用代码:
data.array
它总是给我零,我该怎么办?
我也尝试过data.arrayValue
和data.arrayValue.map {$0.stringValue}
解决方法
假设您的数据结构是
[
{
"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转换为实体,同时遵守可编码协议
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,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)
}
}
}
}
不能确保它对您的情况有用
如果无法解决,请提供更多详细信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。