gpt4 book ai didi

ios - 没有模型无法解析json

转载 作者:行者123 更新时间:2023-11-28 11:29:51 25 4
gpt4 key购买 nike

我正在调用 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
}
}

提示:不要在 swift 中使用 NS 东西并且避免使用 Data(contentsOf: 因为它会阻塞主线程

关于ios - 没有模型无法解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57145554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com