我想找到一种解析JSON数组的解决方案。有我解析JSON的代码,但是我想要一个没有for语句的解决方案,我可以解析数组。

解析代码:

func parsigJsonData(resultArray:any?){

  if let resultArray = resultDic["trucks"] as? BaseModelData {
        print(resultArray)
     }
}


    class BaseModel {
 public typealias BaseModelData = (id:String?,title:String?,select:Bool)

      var id : String?
      var title : String?
      var select : Bool = false

      init(json: [String:Any]) {
        self.id = json["id"] as? String
        self.title = json["title"] as? String
        self.select = false
      }
    }
extension BaseModel {

  var tableRepresentation: [BaseModelData] {
    return [(id:id,title:title,select:select)]
  }
}


结果数组包含baseModel对象的列表。我尝试使用此代码进行解析,但无法正常工作,并且无法成功将其强制转换为BaseModelData。
是否有没有for语句的解析JSON数组的解决方案?
感谢您的解决方案。

有我的json响应样本:

{“ trucks”:[{“ id”:“ 1”,“ title”:“ \ u062e \ u0627 \ u0648 \ u0631 \ u062a \ u0627 5 \ u062a \ u0646 \ u0627 \ u062a \ u0627 \ u0642 \ u0686 \ u0648 \ u0628 \ u06cc“},{” id“:” 2“,” title“:” \ u062e \ u0627 \ u0648 \ u0631 \ u062a \ u0627 5 \ u062a \ u0646 \ u06a9 \ u0645 \ u067e \ u0631 \ u0633 \ u06cc“ },{“ id”:“ 3”,“ title”:“ \ u062e \ u0627 \ u0648 \ u0631 \ u062a \ u0627 8 \ u062a \ u0646 \ u0627 \ u062a \ u0627 \ u0642 \ u0686 \ u0648 \ u0628 \ u06cc },{“ id”:“ 4”,“ title”:“ \ u062e \ u0627 \ u0648 \ u0631 \ u062a \ u0627 8 \ u062a \ u0646 \ u06a9 \ u0645 \ u067e \ u0631 \ u0633 \ u06cc”},{“ id“:” 5“,” title“:” \ u062e \ u0627 \ u0648 \ u0631 \ u06cc \ u062e \ u0686 \ u0627 \ u0644 \ u062f \ u0627 \ u0631“}”

最佳答案

Swift 4使您变得非常简单。只需添加可解码协议,

struct BaseModel: Codable {
      var id : String?
      var title : String?
      var select : Bool = false
}


并使用它来检索数据:

func makeRequest(completionHandler: @escaping ([BaseModel]?, Error?) -> Void) {

var urlRequest = URLRequest(url: url)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request as URLRequest){
                (data, response, error) in
                guard let responseData = data else {
                    print("Error: did not receive data")
                    completionHandler(nil, error)
                    return
                }
                guard error == nil else {
                    completionHandler(nil, error)
                    return
                }

                let decoder = JSONDecoder()
                do {
                    let dataObject = try decoder.decode([BaseModel].self, from: responseData)
                    completionHandler(dataObject, nil)
                } catch {
                    print("error trying to convert data to JSON")
                    print(error)
                    completionHandler(nil, error)
                }
}

task.resume()
}

关于json - 解析不带for语句的JSON数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47461433/

10-09 22:33