【问题标题】:How to access JSON data from URL in Swift 5如何在 Swift 5 中从 URL 访问 JSON 数据
【发布时间】:2019-10-01 18:11:12
【问题描述】:

我正在从网站的 JSON 列表创建数据列表。但是, URLSession.shared.dataTask 正在返回空数据。

我试过在 URLSession.shared.dataTask、JSONSerilization、JSONDecoder、不同形式的 URL 的函数之外打印

我已经为此工作了将近一个星期,但我仍然无法弄清楚问题所在。我现在的主要猜测是这是因为我在函数内部打印,但是从在线教程中我看到它们都在内部打印。

任何帮助将不胜感激! :)

if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!){
            URLSession.shared.dataTask(with: url) { (data, response, error) in

                guard let data = data else {
                    print("Data != Data")
                    return

                }

                let dataStr = String(decoding: data, as: UTF8.self)
                print("DataStr" + dataStr) //Empty


                do {
                    let dataParse = try? JSONDecoder().decode(OuterData.self, from: data)
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

                    print(dataParse) //nil
                    print(json)//empty data


                } catch let jsonError {
                    print ("jsonError")
                    print (jsonError)
                }

            }.resume()

//Created from https://app.quicktype.io/#l=go

struct Suggestion: Codable {
    let id: String
    let name: String
    let audience_size: Int
    let path = [String]()
    let description: String?
    let topic: Topic?
    let disambiguation_category: String?

    enum CodingKeys: String, CodingKey {
        case id, name
        case audience_size = "audience_size"
        case path
        case description = "description"
        case topic
        case disambiguation_category = "disambiguation_category"
    }
}

struct OuterData: Codable{
    let dataSuggestion: [Suggestion]
}

enum Topic: String, Codable {
    case businessAndIndustry = "Business and industry"
    case education = "Education"
    case foodAndDrink = "Food and drink"
    case hobbiesAndActivities = "Hobbies and activities"
    case lifestyleAndCulture = "Lifestyle and culture"
    case newsAndEntertainment = "News and entertainment"
    case people = "People"
    case shoppingAndFashion = "Shopping and fashion"
    case sportsAndOutdoors = "Sports and outdoors"
    case technology = "Technology"
    case travelPlacesAndEvents = "Travel, places and events"
}

预期输出:

{
   "data": [
      {
         "id": "6008740787350",
         "name": "Business and industry",
         "audience_size": 1759626900,
         "path": [
            "Interests",
            "Business and industry"
         ],
         "description": ""
      },
      {
         "id": "6003402305839",
         "name": "Business",
         "audience_size": 1231141110,
         "path": [
            "Interests",
            "Business and industry",
            "Business"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6003248297213",
         "name": "Product (business)",
         "audience_size": 935729470,
         "path": [
            "Interests",
            "Additional Interests",
            "Product (business)"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6004037932409",
         "name": "Management",
         "audience_size": 323096480,
         "path": [
            "Interests",
            "Business and industry",
            "Management"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6002840040679",
         "name": "Music industry",
         "audience_size": 251698230,
         "path": [
            "Interests",
            "Additional Interests",
            "Music industry"
         ],
         "description": null,
         "topic": "News and entertainment"
      },
      {
         "id": "6002884511422",
         "name": "Small business",
         "audience_size": 87865033,
         "path": [
            "Interests",
            "Business and industry",
            "Small business"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6003165841322",
         "name": "Distribution (business)",
         "audience_size": 79327710,
         "path": [
            "Interests",
            "Additional Interests",
            "Distribution (business)"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003342222945",
         "name": "Show business",
         "audience_size": 69642870,
         "path": [
            "Interests",
            "Additional Interests",
            "Show business"
         ],
         "description": null,
         "topic": "News and entertainment"
      },
      {
         "id": "6002932439173",
         "name": "Subscription business model",
         "audience_size": 64490740,
         "path": [
            "Interests",
            "Additional Interests",
            "Subscription business model"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003464157303",
         "name": "Business Insider",
         "audience_size": 62085690,
         "path": [
            "Interests",
            "Additional Interests",
            "Business Insider"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003190330534",
         "name": "Order (business)",
         "audience_size": 60961920,
         "path": [
            "Interests",
            "Additional Interests",
            "Order (business)"
         ],
         "description": null,
         "topic": "Travel, places and events"
      },
    ...
}

【问题讨论】:

  • 离题了,但是当您执行try? 时,围绕解码调用的执行/捕获毫无意义,因此请删除问号。
  • Postman 中试试这个网址,看看你会得到什么。似乎 api 无法正常工作。您的代码看起来不错。
  • let dataParse = try? JSONDecoder().decode(OuterData.self, from: data) 相同评论:stackoverflow.com/questions/58169372/…

标签: json swift


【解决方案1】:

简单替换

let dataSuggestion: [Suggestion]

let data: [Suggestion]

除非您添加 CodingKeys,否则结构成员的名称必须与相应的 JSON 键匹配。

并且 - 正如 cmets 中所建议的 - 始终删除 try? 中的问号 do - catch

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多