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.arrayValuedata.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)
            }
        }
    }
}

不能确保它对您的情况有用

如果无法解决,请提供更多详细信息。