I just can not figure out how to parse a JSON of this format. You need to get a photo, teaser, tags and. etc.

{ "response": { "count": 1722, "items": { "1871": { "id": "1871", "title": "На сахалинской мараловой ферме готовятся добывать панты", "slug": "1871-na-sahalinskoi-maralovoi-ferme-gotovjatsja-dobyvat-panty", "seo_keys": "рогов, фермы, мараловой, проходить, пантов, комплекс, мараловой фермы", "seo_desc": "На мараловой ферме готовятся добывать панты. В настоящий момент на ферме, которая находится в селе Новиково Корсаковского района, происходит отбивка самцов от самок. Для дальнейшей резки у самцов рогов. Процесс это сложный.", "seo_title": null, "tags": "фермы, рогов, комплекс, проходить, пантов, мараловой, мараловодов, маралов, комплекса, воздухом", "date_pub": "2017-06-21 09:48:06", "date_last_modified": "2017-06-21 09:48:06", "date_pub_end": null, "is_pub": "1", "hits_count": "1", "user_id": "1", "parent_id": null, "parent_type": null, "parent_title": null, "parent_url": null, "is_parent_hidden": null, "category_id": "16", "folder_id": null, "is_comments_on": "1", "comments": "0", "rating": "0", "is_deleted": null, "is_approved": "1", "approved_by": null, "date_approved": null, "is_private": "0", "teaser": "На мараловой ферме готовятся добывать панты. В настоящий момент на ферме, которая находится в селе Новиково Корсаковского района, происходит отбивка самцов от самок. Для дальнейшей резки у самцов рогов. Процесс это сложный. Проходит под контролем двух экспертов — мараловодов, которые приехали работать на Сахалин из республики Алтай. Основная задача — загнать всех маралов в вольер. Для этого сотрудники фермы образуют живой коридор, чтобы животные не смогли проскочить. В вольере будет проходить осмотр всего поголовья оленей. Далее самки будут выпущены, а самцы останутся до созревания рогов.<a class=\"read-more\" href=\"/news/1871-na-sahalinskoi-maralovoi-ferme-gotovjatsja-dobyvat-panty.html\">Подробнее</a>", "photo": null, "user_nickname": "Администратор", "folder_title": null }, "1872": { "id": "1872", "title": "Ксения Лыгина из областного центра заняла первое место на конкурсе \"Островки живой природы в поселениях Сахалина\"", "slug": "1872-ksenija-lygina-iz-oblastnogo-centra-zanjala-pervoe-mesto-na-konkurse-ostrovki-zhivoi-prirody-v-", "seo_keys": "из южно сахалинска", "seo_desc": "Региональное управление Роспотребнадзора провело экологический конкурс фотографий \"Островки живой природы в поселениях Сахалина\". Всего в мероприятии участвовали 11 авторов, которые прислали 145 фотографий.", "seo_title": null, "tags": "фотографий, из южносахалинска, с фотографией, место, авторов, роспотребнадзора, конкурса, соответствовали, и были, на сайте", "date_pub": "2017-06-21 10:00:16", "date_last_modified": "2017-06-21 10:00:16", "date_pub_end": null, "is_pub": "1", "hits_count": "1", "user_id": "1", "parent_id": null, "parent_type": null, "parent_title": null, "parent_url": null, "is_parent_hidden": null, "category_id": "17", "folder_id": null, "is_comments_on": "1", "comments": "0", "rating": "0", "is_deleted": null, "is_approved": "1", "approved_by": null, "date_approved": null, "is_private": "0", "teaser": "Региональное управление Роспотребнадзора провело экологический конкурс фотографий \"Островки живой природы в поселениях Сахалина\". Всего в мероприятии участвовали 11 авторов, которые прислали 145 фотографий. Из них условиям конкурса соответствовали 72 фото 6 авторов, которые и были опубликованы на сайте управления. По итогам голосования членов жюри определились победители фотоконкурса. Так, первое место заняла Ксения Лыгина из Южно-Сахалинска с фотографиями \"Городской оазис\" и \"На пляжном острове\".<a class=\"read-more\" href=\"/news/1872-ksenija-lygina-iz-oblastnogo-centra-zanjala-pervoe-mesto-na-konkurse-ostrovki-zhivoi-prirody-v-.html\">Подробнее</a>", "photo": null, "user_nickname": "Администратор", "folder_title": null }, 

Generally pulled data through SwiftyJSON + Alomofire. Now it is stalled at the stage of transferring this data to the TableView.

At this stage, the code is.

I do not understand how to transfer the values ​​obtained in getJSON to another function (in the Table). For the test, I made a pGET function that simply prints the contents of the array. So, outside the getJSON function, this array is empty. How to transfer values ​​from this function to other functions? Help me please )

I study Swift for 1 week, I ask you not to judge strictly for the coarseness of the code, I have not been involved in programming at all before.

 import UIKit import Alamofire import SwiftyJSON class ViewController: UIViewController { var resFuncValue = "" @IBOutlet weak var tableView: UITableView! var arrRes = [[String:AnyObject]]() //Array of dictionary override func viewDidLoad() { super.viewDidLoad() getJSON() pGet() } func getJSON() { Alamofire.request("http://okha65.ru/api/method/content.get.news?api_key=534aeea9ee6176f0fd59d5527da4dd74a1").responseJSON { (responseData) -> Void in if((responseData.result.value) != nil) { let swiftyJsonVar = JSON(responseData.result.value!) if let resData = swiftyJsonVar["response"].dictionary { if let resItems = resData["items"]?.dictionary { for Count in resItems { if let resID = resItems[Count.key]?.dictionary { let resTitle = resID["teaser"]?.string self.resFuncValue.append(resTitle!) //self.resValue = [resTitle] // print("Титл \(resTitle)") } } } } } } } func pGet() { print([self.resFuncValue]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 
  • And what exactly is the format? How and what are you doing? That does not work? - VAndrJ
  • I had to write, not with a comment, but with an answer, for the restriction on symbols - Igor Strelov
  • In what form does this come to you from the network layer? Data, String, [String: Any]? The starting point is not clear, there are no technical details. - Eugene Krivenja
  • And without technical details, the answer is simple: come json, take it and parse it. Swift code examples on kilometers. - Eugene Krivenja

1 answer 1

This should help. Https://github.com/SwiftyJSON/SwiftyJSON has code examples for standard parsing and using

Well, your code would look something like this.

 let myLson = try JSONSerialization..... let parsArray = myJson as? [String:Any] let secondArray = parsArray["response"]! as? [String:Any] let thirdArray = secondArray["items"]! as? Dictionary<String, Any> for item in thirdArray! { let newItem = item.value as? [String:Any] print(newItem!["photo"] ?? "nil") print(newItem!["teaser"] ?? "nil") print(newItem!["tags"] ?? "nil") } 

Upd

var resFuncValue = "" // not an array but a string


 func getJSON(completion:(_ success:Bool,_ array:[String]) -> Void) { Alamofire.request("http://okha65.ru/api/method/content.get.news?api_key=534aeea9ee6176f0fd59d5527da4dd74a1").responseJSON { (responseData) -> Void in if((responseData.result.value) != nil){ var result:[String] = [] let swiftyJsonVar = JSON(responseData.result.value!) if let resData = swiftyJsonVar["response"].dictionary { if let resItems = resData["items"]?.dictionary { for Count in resItems { if let resID = resItems[Count.key]?.dictionary { let resTitle = resID["teaser"]?.string result.append(resTitle) } } completion(true,result) } } } } } 

and method call

 self.getJSON(){ (success,result) in if success { print(result) //или можно делать любые другие действия с вашим масcивом } } 
  • Thank you very much. And how do I transfer the result value to the table cell now? A little did not understand where the method will be called. From a table function, can I call it? - Igor Strelov
  • it is better to write the data to a variable before displaying the table and transfer it as a parameter to your UITableViewController - Andrey Iskamov
  • By your variant of the function, nothing happened. Does not give value to it. In principle, and with my option the same. Inside the function, everything is fine parsed. Why I don’t understand other functions ... - Igor Strelov
  • corrected the error in the code "result.append (resTitle)" and may need to change func getJSON (completion: (_ success: Bool, _ array: [String]) -> Void) to func getJSON (completion: @escaping (_ success: Bool, _ array: [String]) -> Void) And show how you call the getJSON () method - Andrey Iskamov