如何在SWIFT中解析JSONObject

时间:2019-07-07 13:17:52

标签: json swift

我有一个api文件,该文件返回以下WebApplicationContext

JSONObject

我可以解析其JSONArray

{"result":[{"eventID":"1","regionID":"2","venue":"Saxafi Hotel","eventName":"VDATE","startDateTime":"2019-04-17 16:00:00","endDateTime":"2019-04-18 21:30:00"}]}

[{"eventID":"1","regionID":"2","venue":"Saxafi Hotel","eventName":"VDATE","startDateTime":"2019-04-17 16:00:00","endDateTime":"2019-04-18 21:30:00"}]

我在func parseJSON(_ data: Data){ var jsonResult = NSArray() do{ jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray }catch let error as NSError{ print(error) } var jsonElement = NSDictionary() let stocks = NSMutableArray() for i in 0 ..< jsonResult.count { jsonElement = jsonResult[i] as! NSDictionary let stock = StockModel() if let name = jsonElement["venue"] as? String, let price = jsonElement["regionID"] as? String { print(name) print(price) stock.name = name stock.price = price } stocks.add(stock) } DispatchQueue.main.async(execute: {() -> Void in self.delegate.itemsDownload(items: stocks) }) } 中是陌生的,在IOS中我很熟悉,而且我过去一直在解析

Android

2 个答案:

答案 0 :(得分:1)

您的数据类型如下,

// MARK: - Response
struct Response: Codable {
    let result: [Result]
}

// MARK: - Result
struct Result: Codable {
    let eventID, regionID, venue, eventName: String
    let startDateTime, endDateTime: String
}

//从API获取数据并解码响应,如下所示,

do {
    let response = try JSONDecoder().decode(Response.self, from: data)
    response.result.forEach { result in
       print(result.eventName)
    }
} catch {
    print(error)
}

答案 1 :(得分:0)

您可以尝试

struct Root:Codable { 
    let result:[Result]
}

struct Result:Codable {
    let eventID,regionID,venue,eventName:String
    let startDateTime,endDateTime:Date
}

        do {

            let dec = JSONDecoder()
            let df = DateFormatter()
            df.dateFormat = "yyy-MM-dd HH:mm:ss"
            dec.dateDecodingStrategy = .formatted(df)
            let res  = try dec.decode(Root.self, from:data)
        }
        catch {
            print(error)
        }

或者您可以摆脱Root并这样做

        do {

            let con = try JSONSerialization.jsonObject(with:data) as! [String:Any]
            let www = try JSONSerialization.data(withJSONObject:con["result"]!)
            let dec = JSONDecoder()
            let df = DateFormatter()
            df.dateFormat = "yyy-MM-dd HH:mm:ss"
            dec.dateDecodingStrategy = .formatted(df)
            let res  = try dec.decode([Result].self, from:www)
            print(res)
        }
        catch {
            print(error)
        }