我想在我的 iOS 选项卡栏应用程序中解析来自不同 URL 的 JSON 字符串:
- 解析.swift
- FirstViewController.swift(初始标签栏 View Controller )
- SecondViewController.swift
- ...
在 Parsing.swift 中,我在 Playground 中控制了各种 struct (TopLevel)和 enum 方案:它们工作得很好。在每个 ViewController 中,我都有一个 TableView ,我想用不同 JSON 解析的结果来填充它。这是我的简化代码:
FirstViewController.swift viewDidLoad()
let url = // my first URL to parse
let urlObj = URL(string: url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlObj!) { (data, response, error) in
do {
let results = try JSONDecoder().decode(TopLevel.self, from: data!)
... for ...
self.table.reloadData()
}
catch {
...
}
}
task.resume()
此代码工作完美:当应用程序首次打开时,FirstViewController 中的 TableView 会填充来自 url 的 JSON 解析结果。但现在是时候单击第二个栏项来打开 SecondViewController 了。代码显然是:
SecondViewController.swift viewDidLoad()
let url2 = // my second URL to parse
let urlObj2 = URL(string: url2)
let config2 = URLSessionConfiguration.default
let session2 = URLSession(configuration: config2)
let task2 = session.dataTask(with: urlObj2!) { (data2, response2, error2) in
do {
let results2 = try JSONDecoder().decode(TopLevel.self, from: data2!)
... for ...
self.table2.reloadData()
}
catch {
...
}
}
task2.resume()
好吧,当我点击第二个选项卡栏项打开 SecondViewController 时, TableView 不会填充,并且 XCode 会给出错误:dataCorrupted(Swift.DecodingError.Context(codingPath: [],debugDescription:“给定的数据不是有效的 JSON。”,underlyingError:可选(Error Domain = NSCocoaErrorDomain Code = 3840“JSON 文本未以数组或对象开头,且允许未设置片段的选项。” UserInfo = {NSDebugDescription =JSON 文本未以数组或对象开头,并且未设置允许片段的选项。}))) 但 JSON 文本有效。
我尝试了很多解决方案:我已将任务更改为 URLSession.shared,我使用了私有(private)结构和枚举,我已控制变量和常量,好吧,无法正确解析第二个 URL。即使我创建一个新的单 View 应用程序并将 SecondViewController.swift 代码复制到 viewDidLoad() 函数中,它也可以完美工作,所以,再说一遍,这不是第二个 URL(JSON)的问题字符串有效。我认为两个解析任务之间存在干扰,看起来第一个解析任务损坏了第二个解析任务。我能做些什么?谢谢。
编辑:这是我的 JSON(所有字段都是有效字符串,为了简化我已将其删除)
{
"attributes": {
"version": "2.0",
"nodeValue": "\n"
},
"channel": {
"title": " ",
"link": " ",
"description": " ",
"lastBuildDate": " ",
"language": " ",
"copyright": " ",
"item": [
{
"title": " ",
"link": " ",
"guid": {
"attributes": {
"isPermaLink": "false",
"nodeValue": " "
}
},
"pubDate": " ",
"category": " "
},
{
"title": " ",
"link": " ",
"guid": {
"attributes": {
"isPermaLink": "false",
"nodeValue": " "
}
},
"pubDate": " ",
"category": " "
}
]
} }
最佳答案
因为我无权访问 JSON 响应和使用的模型。 我可以假设几种可能导致此问题的可能性。
1) 您有模型和 JSON 响应。当您尝试解码时,JSON 响应中可能有任何字段为 null,并且模型中的相同属性不是可选的。
2) 模型可能不具有与 JSON 响应相同的结构(属性)。
关于ios - Swift 中从不同 URL 解析多个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785747/