如何将 JSON 数据存储到 swift3 中的数组(模型类)中?

Posted

技术标签:

【中文标题】如何将 JSON 数据存储到 swift3 中的数组(模型类)中?【英文标题】:How to store the JSON data into array(model class) in swift3? 【发布时间】:2017-01-27 14:23:06 【问题描述】:

当我尝试将 JSON 数据存储到数组中时,我得到了 nils。 我想正确获取 JSON 数据

这是 APIManager 类上print(articles) 的结果

[AppName.Article(author: nil, description: nil, publishedAt: nil, title: nil, url: nil, urlToImage: nil), AppName.Article(author: nil, description: nil, publishedAt: nil, title: nil, url: nil, urlToImage: nil)]

我在下面有三个类和 API 数据。 文章

import Foundation
import SwiftyJSON

struct Article 

var author: String!
var description: String!
var publishedAt: String!
var title: String!
var url: String!
var urlToImage: String!


init(json: JSON) 
    self.publishedAt = json["publishedAt"].string
    self.author = json["author"].string
    self.title = json["title"].string
    self.description = json["desctiption"].string
    self.url = json["url"].string
    self.urlToImage = json["urlToImage"].string


//    init(author: String, discription:String, publishedAt: String, title:    String,    url: String, urlToImage: String) 
//        self.author = author
//        self.discription = discription
//        self.publishedAt = publishedAt
//        self.title = title
//        self.url = url
//        self.urlToImage = urlToImage
//    

API 管理器

import Foundation
import Alamofire
import SwiftyJSON

class APIManager 

class func getArticle(handler: @escaping (Array<Article>?) -> ()) 
    Alamofire.request(
        "https://newsapi.org/v1/articles?source=techcrunch&apiKey=XXX"
    )
    .responseJSON  response in
        guard response.result.isSuccess else 
            print("Error while fetching jsondata: \(response.result.error)")
            return
        

        guard let responseJSON = response.result.value else 
            print("Invalid jsondata received from the server")
            return
        

        var articles: Array<Article> = []
        let json = JSON(responseJSON)
        //print(json)

        json.forEach (_, json) in
            print(json)
            articles.append(Article(json: json))
            print(articles)
        

        handler(articles)
    


视图控制器

    override func viewDidLoad() 
    super.viewDidLoad()

    APIManager.getArticle (articles: Array<Article>?) in
        if let data = articles?[0] 

            print(data)

        
    

API 数据


articles =     (
            
        author = "Matthew Lynley";
        description = "Google reported mixed earnings for its fourth quarter today \U2014 but we're starting to see some flashes of improvement in its \"other bets\" category, which is..";
        publishedAt = "2017-01-26T20:09:05Z";
        title = "Alphabet\U2019s bets beyond search are starting to pay\U00a0off";
        url = "http://social.techcrunch.com/2017/01/26/alphabets-bets-beyond-search-are-starting-to-look-better/";
        urlToImage = "https://tctechcrunch2011.files.wordpress.com/2016/07/a3c4057e7d804c79b4bfb3278f4afced.jpg?w=764&h=400&crop=1";
    ,

            
        author = "Natasha Lomas";
        description = "An Executive Order signed by U.S. President Donald Trump in his first few days in office could jeopardize a six-month-old data transfer framework that enables..";
        publishedAt = "2017-01-26T15:41:33Z";
        title = "Trump order strips privacy rights from non-U.S. citizens, could nix EU-US data\U00a0flows";
        url = "http://social.techcrunch.com/2017/01/26/trump-order-strips-privacy-rights-from-non-u-s-citizens-could-nix-eu-us-data-flows/";
        urlToImage = "https://tctechcrunch2011.files.wordpress.com/2017/01/gettyimages-632212696.jpg?w=764&h=400&crop=1";
    ,

sortBy = top;
source = techcrunch;
status = ok;

如果您需要更多信息,请告诉我。 谢谢。

【问题讨论】:

【参考方案1】:

您需要从您的JSON 访问articles 数组并循环访问它以获取Article 的数组。

let json = JSON(responseJSON)
//Get the Array of articles(JSON)
let articleArray = json["articles"].arrayValue
//Now loop through this array.
articleArray.forEach (json) in
    print(json)
    articles.append(Article(json: json))
    print(articles)

【讨论】:

我可以得到我想要的结果。感谢您的快速回答! @tekun 欢迎朋友 :) 当我在 json["article"] 之后附加 .arrayValue 时,出现以下错误 Contextual closure type'(JSON) -> Void'expects 1 argument。但 2 用于闭包体 但是,当我将 (_, json) 更改为 (json) 时,错误消失了。这是收集解决方案吗??

以上是关于如何将 JSON 数据存储到 swift3 中的数组(模型类)中?的主要内容,如果未能解决你的问题,请参考以下文章

如何将计时器中的数据传递给新的 ViewController (Swift 3)

试图将 JSON 解析为 swift3 并显示到 UILabel

如何通过 python 将 JSON 数据附加到存储在 Azure blob 存储中的现有 JSON 文件?

如何在没有 segue 的情况下在 Swift 3 中将数据从 VC 传递到另一个?

如何使用 SWIFT3 解析此 JSON [重复]

如何将json中的数据存储在sql表中(python)