【问题标题】:parsing array in array into some arrays in swift 4?将数组中的数组解析为swift 4中的一些数组?
【发布时间】:2017-10-15 12:31:40
【问题描述】:

我在我的新闻 api 代码中使用了解析子

儿子是这样的

> {
"status": "ok",
"source": "associated-press",
"sortBy": "top",
-"articles": [
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
"title": "Pro-Trump states most affected by his health care decision",
"description": "President Donald Trump's decision to end a provision of the Affordable Care Act that was benefiting roughly 6 million Americans helps fulfill a campaign promise",
"url": "https:urlexample",
"urlToImage": "url example",
},
-{
"author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
"title": "Pro-Trump states most affected by his health care decision",
"description": "President Donald Trump's decision to end a provision of the Affordable Care Act that was benefiting roughly 6 million Americans helps fulfill a campaign promise",
"url": "https:urlexample",
"urlToImage": "url example",
},
    ]
     }

正如您在每个数组中看到的,我们有标题 - 描述等 我想将此 jason 解析为单独的数组,例如将所有标题附加到一个数组中,并将所有描述附加到另一个数组中等等

这是我的代码

struct Response : Decodable {
let articles: articles
}

struct articles: Decodable {

let title: String
let description : String
let url : String
let urlToImage : String
}

这里是json的代码

let jsonUrl = "https://newsapi.org/[your codes]"

        guard let url = URL(string : jsonUrl) else {
            return
        }

        URLSession.shared.dataTask(with: url) { (data , response , error) in

            guard let data = data else {return}

            do {

                let article =  try JSONDecoder().decode(Response.self , from : data)

                print(article.articles.title)
                print(article.articles.description)
                print(article.articles.url)
                print(article.articles.urlToImage)

            }
            catch {

                print(error)

            }


        }.resume()

当我运行它时,我会收到这个错误

“本应解码字典,但找到了一个数组。”,underlyingError: nil))

【问题讨论】:

    标签: ios arrays json swift swift4


    【解决方案1】:

    首先,要区分属性/方法名和类型名,尽量遵循Swift命名约定:(以下来自Swift API Design guidelines

    类型和协议的名称是 UpperCamelCase。其他的都是lowerCamelCase。

    此外,您的 articles 结构仅代表一篇文章的数据,而不是多篇文章。所以它应该以大写A开头,并且是单数:

    struct Article: Decodable {
    

    其次,如果您再看看返回的 JSON,文章是一个 array 字典:

    -"articles": [
    -{
    "author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
    ...
    },
    -{
    "author": "CHRISTINA A. CASSIDY and MEGHAN HOYER",
    ...
    },
    

    所以Response 结构中的articles 属性应该是Article 的数组。

    struct Response : Decodable {
        let articles: [Article]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 2018-05-31
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多