我正在尝试从json文件data.json中读取数据,但是每当我尝试解析并显示数据时,都会出现标题中提到的错误。
我正在尝试使用可编码协议解析json,但似乎找不到给定错误的解决方案。
HomeTabViewController.swift
import UIKit
import FirebaseAuth
class HomeTabViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//MARK: - Global Variables
var articles = [Article]()
// MARK: - Outlets
@IBOutlet weak var newsTableViewOutlet: UITableView!
// MARK: - Default Functions
override func viewDidLoad() {
super.viewDidLoad()
self.newsTableViewOutlet.dataSource = self
self.newsTableViewOutlet.delegate = self
if let localData = self.readLocalFile(forName: "data") {
self.parse(json: localData)
}
}
// MARK: - TableView Functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = newsTableViewOutlet.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath)
let article = self.articles[indexPath.row]
cell.textLabel?.text = article.title
print(article.title)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let rotationTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 30, 0)
cell.layer.transform = rotationTransform
cell.alpha = 0.5
UIView.animate(withDuration: 0.75) {
cell.layer.transform = CATransform3DIdentity
cell.alpha = 1.0
}
}
// MARK: - Data Download Functions
// Function to parse JSON
func parse(json: Data){
let decoder = JSONDecoder()
if let newsArticles = try? decoder.decode(Articles.self, from: json){
self.articles = newsArticles.articles
newsTableViewOutlet.reloadData()
}
}
func readLocalFile(forName name: String) -> Data? {
do {
if let bundlePath = Bundle.main.path(forResource: name,
ofType: "json"),
let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
return jsonData
}
} catch {
print(error)
}
return nil
}
// MARK: Segue Functions
@IBAction func unwindToRootViewController(segue: UIStoryboardSegue) {
print("Unwind to Root View Controller")
}
@IBAction func logOutPressed(_ sender: UIButton) {
print("Log out Button Pressed")
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
Article.swift
struct Article: Codable{
public var title: String
public var description: String
}
Articles.swift
struct Articles: Codable {
public var articles: [Article]
}
data.json
{
"status": "ok",
"totalResults": 38,
"articles": [
{},
{
"source": {},
"author": null,
"title": "Blair approves request to boost RCMP presence as Nova Scotia lobster fishery dispute escalates - CBC.ca",
"description": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitter conflict over a First Nations lobster harvest in that pro…",
"url": "https://www.cbc.ca/news/politics/nova-scotia-fishery-conflict-rcmp-1.5766838",
"urlToImage": "https://i.cbc.ca/1.5554196.1588555323!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/ns-shootings-20200420.jpg",
"publishedAt": "2020-10-17T21:16:00Z",
"content": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitt… [+4949 chars]"
},
{
"source": {
"id": null,
"name": "Maple Leafs Hot Stove"
},
"author": "Kevin Papetti",
"title": "Toronto Maple Leafs Offseason: Joe Thornton signing, the odd man out, and the next steps - Maple Leafs Hot Stove",
"description": "What an active week -- and offseason overall -- it's been for Kyle Dubas and the Toronto Maple Leafs. In: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey Anderson (RW), Travis Boyd (C/LW), Aaron Dell (G), Fi…",
"url": "https://mapleleafshotstove.com/2020/10/17/toronto-maple-leafs-offseason-joe-thornton-signing-the-odd-man-out-and-the-next-steps/",
"urlToImage": "https://46wvda23y0nl13db2j3bl1yx-wpengine.netdna-ssl.com/wp-content/uploads/2020/10/jumbo-joe-scaled.jpeg",
"publishedAt": "2020-10-17T20:39:00Z",
"content": "What an active week and offseason overall its been for Kyle Dubas and the Toronto Maple Leafs.\r\nIn: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey… [+10814 chars]"
},
{
"source": {
"id": null,
"name": "AppleInsider"
},
"author": "Malcolm Owen",
"title": "Early MagSafe Charger, iPhone 12 accessory orders start arriving - AppleInsider",
"description": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arriving ahead of the iPhone 12 range.",
"url": "https://appleinsider.com/articles/20/10/17/magsafe-chargers-iphone-12-accessory-orders-start-arriving-with-customers",
"urlToImage": "https://photos5.appleinsider.com/gallery/38304-72729-magsafe-charger-xl.jpg",
"publishedAt": "2020-10-17T19:46:39Z",
"content": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arr… [+1533 chars]"
},
{
"source": {
"id": null,
"name": "Global News"
},
"author": "Simon Little",
"title": "Anti-mask protesters cause disturbance on B.C. ferry, cause unloading delay - Global News",
"description": "A group of about 12 unmasked protesters became belligerent and harassed masked passengers on a morning sailing, according to BC Ferries.",
"url": "https://globalnews.ca/news/7403621/anti-mask-protesters-cause-disturbance-delay-b-c-ferry/",
"urlToImage": "https://globalnews.ca/wp-content/uploads/2018/02/01172660.jpg?quality=85&strip=all&crop=0px%2C111px%2C3000px%2C1579px&resize=720%2C379",
"publishedAt": "2020-10-17T19:30:51Z",
"content": "A group of anti-mask protesters has been banned from BC Ferries for the rest of the day after causing a disturbance on a morning sailing from Nanaimo to Horseshoe Bay.\r\nThe incident happened on the 8… [+2038 chars]"
},
{
"source": {
"id": "cbc-news",
"name": "CBC News"
},
"author": null,
"title": "Chechen teen killed by police named as suspect in teacher's beheading in France - CBC.ca",
"description": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on social media minutes after the attack, officials said Saturday.",
"url": "https://www.cbc.ca/news/world/france-teacher-beheading-chechen-1.5766742",
"urlToImage": "https://i.cbc.ca/1.5766755.1602956271!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/aptopix-france-teacher-decapitated.jpg",
"publishedAt": "2020-10-17T18:43:00Z",
"content": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on so… [+5743 chars]"
}
}
答案 0 :(得分:1)
似乎JSON无效。我通过jsonlint.com来运行它
我还删除了顶部的空白文章。从JSON数据实例化const fileStream = fs.createReadStream('./fake.swu');
async function postFormToIPs(){
for (let i = 0; i < 2; i++){
console.log(i);
var f = new FormData();
f.append('password', 'wrong')
f.append('swupdate.swu', fileStream)
const { body } = await got.post('http://postman-echo.com/post', {
body: f,
timeout: 5000
});
console.log(body)
}
}
时,可能会导致问题。
这是固定版本:
Article