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

时间:2017-01-27 14:23:07

标签: ios json swift3 alamofire swifty-json

当我尝试将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
//    }
}

APIManager

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)
    }
}
}

的ViewController

    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 个答案:

答案 0 :(得分:0)

您需要从articles访问JSON数组并循环播放,以获取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)
}