2017-01-27 7 views
0

配列にJSONデータを格納しようとすると、私はnilsを取得しました。
私はJSONデータを取得したいが、正しく
JSONデータをswift3の配列(モデルクラス)に保存する方法は?

これは、私は三つのクラスと、以下のAPIデータを持っているprint(articles)

APIManagerクラスの
[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)] 

の結果です。

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


詳細が必要な場合は、お知らせください。
ありがとうございます。

答えて

0

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

私が望む結果を得ることができます。 すぐにお返事ありがとうございます! – tekun

+0

@tekun Welcome mate :) –

+0

json ["article"]の後に.arrayValueをアタッチすると、以下のエラーが発生します コンテキストクロージャタイプ '(JSON) - > Void'expects 1の引数。しかし2はクロージャー本体で使用されました – tekun

関連する問題