簡體   English   中英

沒有模型就無法解析json

[英]Not able to parse json without model

我正在進行api調用並獲得響應,如下所示。

    if let data = NSData(contentsOf: NSURL(string: "http://test.chatongo.in/testdata.json")! as URL) {

        do {
            if let response = try JSONSerialization.jsonObject(with: data as Data, options: []) as? NSDictionary {
                print("THE RESPONSE IS: \(response)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

我得到的回應是……

THE RESPONSE IS: {
    Message = Success;
    Status = 200;
    data =     {
        Records =         (
                        {
                Id = 1;
                collectedValue = 500;
                endDate = "10/06/2018";
                mainImageURL = "http://iphonedeveloperguide.com/oneinr/project1.jpg";
                shortDescription = "This foundation will bring smile on there faces";
                startDate = "05/05/2018";
                title = "Smile Crowdfunding";
                totalValue = 5000;
            },
          {
                Id = 2;
                collectedValue = 750;
                endDate = "08/06/2018";
                mainImageURL = "http://iphonedeveloperguide.com/oneinr/project10.jpg";
                shortDescription = "This foundation will help animals";
                startDate = "05/05/2018";
                title = "Animal Funding";
                totalValue = 20000;
            }
        );
        TotalRecords = 10;
    };
}

但是我該如何解析這個json並從其中獲取包括圖像在內的單個元素,而我無法弄清楚。

你需要

import UIKit

class ViewController: UIViewController {

    var records = [Record]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        URLSession.shared.dataTask(with: URL(string: "http://test.chatongo.in/testdata.json")!) { (data, response, error) in
            guard let data = data else { return }
            do {
                let res = try JSONDecoder().decode(Root.self, from: data)    
                self.records = res.data.records
                 print(res.data.records)
                 // if it's a collection/table wrap the reload here inside DispatchQueue.main.async
            }
            catch {
                print(error)
            }
        }.resume()
    }
}



// MARK: - Empty
struct Root: Codable {
    let status: Int
    let message: String
    let data: DataClass

    enum CodingKeys: String, CodingKey {
        case status = "Status"
        case message = "Message"
        case data
    }
}

// MARK: - DataClass
struct DataClass: Codable {
    let totalRecords: Int
    let records: [Record]

    enum CodingKeys: String, CodingKey {
        case totalRecords = "TotalRecords"
        case records = "Records"
    }
}

// MARK: - Record
struct Record: Codable {
    let id: Int
    let title, shortDescription: String
    let collectedValue, totalValue: Int
    let startDate, endDate: String
    let mainImageURL: String

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case title, shortDescription, collectedValue, totalValue, startDate, endDate, mainImageURL
    }
}

提示:不要快速使用NS東西,並避免使用Data(contentsOf:因為它會阻塞主線程

有多種方法,一種創建模型對象的方法

struct RecordItem : Codable {
var id : Int?
var collectedValue : Int?
var endDate : String?
var mainImageURL: String?
var shortDescription : String?
var title :String?
var startDate : String?
var totalValue : Int?
}
and 
struct Records : Codable {
var items : [RecordItem]?
}

並使用它。 =讓item =數據[index]打印(item.collectedValue),依此類推。

秒方法,您已經創建了dict,然后使用[“ Key”:“ Value”]提取所有鍵和數組對象,並將其設置為任何變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM