简体   繁体   English

Swift中来自不同URL的多个JSON解析

[英]Multiple JSON parsing from different URLs in Swift

I want to parse JSON strings from different URLs in my iOS Tab Bar app: 我想在我的iOS Tab Bar应用中解析来自不同URL的JSON字符串:

  • Parsing.swift Parsing.swift
  • FirstViewController.swift (INITIAL Tab Bar View Controller) FirstViewController.swift(“初始”选项卡栏视图控制器)
  • SecondViewController.swift SecondViewController.swift
  • ... ...

In Parsing.swift I have various struct (TopLevel) and enum schemes I have controlled in Playground: they works perfectly. 在Parsing.swift中,我在Playground中控制了各种struct (TopLevel)和枚举方案:它们完美地工作。 In every ViewController I have a Table View that I want to popolate with results of different JSON parsing. 在每个ViewController中,我都有一个要填充不同JSON解析结果的表视图。 This is my simplified code: 这是我的简化代码:

FirstViewController.swift viewDidLoad() 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()

This code works perfectly : When app first open, Table View in FirstViewController popolates with results of JSON Parsing from url. 这段代码完美地工作 :首次打开应用程序时,FirstViewController中的表视图会使用url的JSON解析结果填充。 But now its time to click on second Bar Item to open SecondViewController. 但是现在该单击第二个Bar Item来打开SecondViewController了。 The code is obviously: 该代码显然是:

SecondViewController.swift viewDidLoad() 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()

Well, when I tap on second Tab Bar Item to open the SecondViewController, Table View don't popolate and XCode gives an error : dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}))) But JSON text is valid . 好吧,当我点击第二个选项卡栏项以打开SecondViewController时,表视图不会显示,并且XCode给出了错误dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。 。,底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840“ JSON文本不是以数组或对象开头,并且选项未设置片段。” UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且选项为允许未设置片段。})))但是JSON文本有效

I have tried a lot of solutions: I've changed tasks to URLSession.shared, I have used private struct and enum, I have controlled variables and costants, well, no way to parse second URL correctly. 我已经尝试了许多解决方案:我将任务更改为URLSession.shared,使用了私有结构和枚举,控制了变量和成本,但是,没有办法正确地解析第二个URL。 Even if I create a NEW Single View App and I copy the SecondViewController.swift code into the viewDidLoad() func, it works perfectly , so, again, its not a problem of the second URL, the JSON strings are valid . 即使我创建一个新的单一视图应用程序,我的SecondViewController.swift代码复制到viewDidLoad中()FUNC,它完美的作品,所以,再一次,它不是第二个URL的问题,JSON字符串是有效的 I think there is an interference between the two parsing tasks, it looks like the first corrupted the second one. 我认为这两个解析任务之间存在干扰,看起来第一个破坏了第二个。 What can I do? 我能做什么? Thanks. 谢谢。

EDIT : this is my JSON (all fields are valid strings, I have deleted it for simplify) 编辑 :这是我的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": " "
          }
      ]
} }

As I don't have access to JSON response and Model used. 由于我无权使用JSON响应和Model。 I can assume few possibilities that may cause this issue. 我可以假设几种可能导致此问题的可能性。

1) You have your model and JSON response. 1)您有模型和JSON响应。 When you are trying to decode, there could any field in JSON response that is null and same property in your model is not made optional. 当您尝试解码时,JSON响应中可能有任何字段为null,并且模型中的相同属性不是可选的。

2) The model may not have same structure (properties) as JSON response. 2)模型的结构(属性)可能与JSON响应不同。

Well, I resolved the issue changing my second URL from "WWW.myserver.net/string2.json" to "myserver.net/string2.json", simply without WWW. 好吧,我解决了将我的第二个URL从“ WWW.myserver.net/string2.json”更改为“ myserver.net/string2.json”的问题,而没有使用WWW。 In this way both tasks works and parses respective strings from different URLs. 这样,两个任务都可以工作并解析来自不同URL的相应​​字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM