繁体   English   中英

如何在swift3中将JSON数据存储到array(model class)中?

[英]How to store the JSON data into array(model class) in swift3?

当我尝试将JSON数据存储到数组中时,显示为nil。
我想正确获取JSON数据

这是在APIManager类上print(articles)的结果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;
}


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

您需要从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)
}

暂无
暂无

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

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