每次我在 API 上发布时,我都会将 Alamofire JSON 响应保存在文件中
{
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:07.515+0000"}
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:14.420+0000"}
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:23.183+0000"}
}
然后我想在表格 View 中显示此响应,我试图反序列化,以便将其放入循环中,它给了我这个错误:
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent("x").appendingPathExtension("json")
var readString = ""
do {
readString = try String(contentsOf: fileURL)
let data = readString.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
let form_name = jsonArray[0]["message"] as? String
print (" midas \(jsonArray) + ")
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}
编辑: 这是我从 Alamofire 灾中救出的东西:
.responseJSON() { response in
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
self.savestrin = utf8Text + "\n"
print("Data: \(self.savestrin)")
}
self.writeToFile(content: self.savestrin )
这是 writetofile 方法
func writeToFile(content: String) {
let documentsPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let filePath = documentsPath.appendingPathComponent("x").appendingPathExtension("json")
//Check if file exists
if let fileHandle = FileHandle(forWritingAtPath: filePath.path) {
//Append to file
fileHandle.seekToEndOfFile()
fileHandle.write(content.data(using: String.Encoding.utf8)!)
}
else {
//Create new file
do {
try content.write(to: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Error creating \(filePath)")
}
}
}
更新: 感谢 Dávid Pásztor 和 vadian,我设法解决了这个问题
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent("x").appendingPathExtension("json")
do {
var readString = try String(contentsOf: fileURL)
let x = readString.components(separatedBy: "\n")
print (" midas \(x) ")
for i in 1..<x.count{
do{
let y = x[i]
print (" midas \(y) ")
let b = convertToDictionary(text: y)
print (" midas1 \(b) ")
let date = try b?["date"]
dictarr["date"] = "\(date)"
print (" midas \(dictarr["date"]) ")
现在的问题是我如何无法在 TableView 中填充它。我尝试过
dictdata.addObject(dictarr) but it gives me error
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let datainrow = dictdata[indexPath.row]
// cell.textLabel?.text = "\(datainrow.objectForKey("message")!)"
// Configure the cell...
return cell
}
最佳答案
这是一个预期的错误,因为您的 JSON 文件无效。您需要将第一个外括号 {}
更改为方括号 []
,因为您要存储字典数组,并且需要使用分隔各个响应逗号。
您的 JSON 应该是这样的:
[
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:07.515+0000"},
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:14.420+0000"},
{"response":99,"message":"You are signing in after Fri Jun 15 10:50:00 EDT 2018.","date":"2018-06-15T14:50:23.183+0000"}
]
你的 JSON 解析器逻辑也有缺陷。您不应该使用 let Reading = readString.components(separatedBy: ",")
将 JSON 分成组件,您应该简单地解析整个 JSON 文件。此外,无需将文件解析为 String
,您可以直接将其读入 Data
并将其传递给 JSONSerialization
。也不需要嵌套的 do-catch
block ,并且 Swift 中 JSON 字典的类型应该是 [String:Any]
,而不是 [String:AnyObject ]
字典数组是 [[String:Any]]
。
do {
let jsonData = try Data(contentsOf: fileURL)
if let jsonArray = try JSONSerialization.jsonObject(with: jsonData) as? [[String:Any]] {
let form_name = jsonArray.first?["message"] as? String
print (" midas \(jsonArray) + ")
} else {
print("bad json")
}
} catch {
print(error)
}
关于ios - 读取json文件并在 TableView 上显示错误:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879180/