0

This is JSON what I want to parse and use in my app

 {
"status": "ok",
"source": "the-next-web",
"sortBy": "latest",
-"articles": [
-{
"author": "Mix",
"title": "Social media giants like Facebook liable to €50M ‘hate speech’ fines in Germany",
"description": "Germany will soon punish social media giants like Facebook, Twitter and YouTube with fines of up to €50 million (approximately $57 million) if they fail to take down illegal or offensive ...",
"url": "https://thenextweb.com/facebook/2017/06/30/facebook-youtube-twitter-germany-50m/",
"urlToImage": "https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/03/facebook.jpg",
"publishedAt": "2017-06-30T15:10:58Z"
},
-{
"author": "Abhimanyu Ghoshal",
"title": "Google’s new Android app makes it easy to save mobile data on the go",
"description": "The good folks at Android Police have spotted a new app from Google called Triangle; it lets you control which other apps can use your mobile data. It's a handy little tool if you're ...",
"url": "https://thenextweb.com/apps/2017/06/30/googles-new-android-app-makes-it-easy-to-save-mobile-data-on-the-go/",
"urlToImage": "https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/06/Triangle-hed.jpg",
"publishedAt": "2017-06-30T13:16:12Z"
},
-{

This is my methods to parse the Json:

typealias GetWeatherSuccess = (_ result: NSDictionary) -> Void
typealias GetWeatherFailure = (_ error: Error?) -> Void

func requestNewsForToday() -> URLRequest {
        let urlText = NewsManager.shared.weatherRequest()
        return URLRequest(url: URL(string: urlText)! as URL)
    }

    func getNews(successHandler: GetWeatherSuccess?,
                    failureHandler: GetWeatherFailure?) {

        let session = URLSession.shared
        let dataTask = session.dataTask(with: requestNewsForToday()) { data, _, error in
            if error == nil {
                if let dic = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                    successHandler?(dic!)
                }
            } else {
                failureHandler?(error)
            }
        }
        dataTask.resume()
    }

And usage of methods:

NetworkManager.shared.getNews(successHandler: { (json: NSDictionary) in

        let articles = json.object(forKey: "articles") as! NSArray
        print(articles[0])
    }) { (_:Error?) in
        print("error")
    }
}

And result is oblivious:

{
    author = "Romain Dillet";
    description = "\U201cWe called this building Station F, like Station France, Station Femmes [ed. note: women in French], Station Founders or Station Freyssinet because..";
    publishedAt = "2017-07-01T09:47:38Z";
    title = "A walk around Station F with Emmanuel\U00a0Macron";
    url = "https://techcrunch.com/2017/07/01/a-walk-around-station-f-with-emmanuel-macron/";
    urlToImage = "https://tctechcrunch2011.files.wordpress.com/2017/06/station-f-emmanuel-macron-9.jpg?w=764&h=400&crop=1";
}

How to take authors String for example? Or make full array of data from json and use it?

Ilya Chikmarev
  • 133
  • 1
  • 11
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – vadian Jul 01 '17 at 16:00
  • As always – do not use Foundation collection types `NSArray / NSDictionary` in Swift. You throw away the strong type information. Use native `Array / Dictionary` – vadian Jul 01 '17 at 16:02

1 Answers1

0

I am going to use Swift 4 Decodable protocol to parse JSON the simple and easy way! It's really a very powerful tool that Apple has given in this update!

By looking at the JSON, I can infer I need two structs which will conform to the Decodable protocol:-

    struct jsonData: Decodable {
      let status: String
      let source: String
      let sortBy: String
      let articles: [Articles]
    }

    struct Articles: Decodable {
     let author: String
     let title: String
     let description: String
     let url: String
     let urlToImage: String
     let publishedAt: String
}

Pay attention that I have exactly named the variables same as your keys in the JSON. This is where the Decodable protocol magic happens. It automatically infers which key value/pair belongs to which variable on the basis of your variable name (meaning your key name in JSON, should be the variable name in swift), provided you named them correctly, otherwise it will throw an error.

Now, making a network connection as usual:-

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

    guard let data = data else { return }

    do {

    let item = try JSONDecoder().decode(jsonData.self, from: data)
    print(item.status) // prints "ok"
    print(items.articles) // prints the 2 arrays in the json, provided in your Question 

    }
    catch let jsonErr {
       print("serialisation error", jsonErr)
    }
}
Dark Innocence
  • 1,389
  • 9
  • 17