Swift:解析动态JSON(Swift: parsing dynamic JSON)

编程入门 行业动态 更新时间:2024-10-23 07:28:21
Swift:解析动态JSON(Swift: parsing dynamic JSON)

我试图解析这个每个对象都有改变键的JSON,试图找到解析每个对象的最佳方式。 我对swift编程非常陌生,所以任何示例代码都会非常有帮助。 我不需要存储所有收到的值,只是特定的字段,如地址,街道名称,图像

JSON输入

{ "a000!%5362657": { "address": "20 Ingram Street", "streetName": "Ingram Street", "streetNumber": "20", "streetDirection": "N", "unitNumber": "", "cityName": "Forest Hills", "countyName": "New York", "state": "NY", "zipcode": "11375", "listingPrice": "$1,151,000", "listingID": "5362657", "remarksConcat": "From nytimes.com: In the comics, Peter Parker, the mild-mannered photojournalist who is Spider-Man's alter ego, grew up at 20 Ingram Street, a modest, two-story boarding house run by his Aunt May in the heart of Forest Hills Gardens. The address actually exists and is home to a family named Parker: Andrew and Suzanne Parker, who moved there in 1974, and their two daughters. In 1989, the family began receiving junk mail addressed to Peter Parker. We got tons of it, Mrs. Parker said yesterday. Star Trek magazines, a Discover Card in his name, and notices from them over the years calling him a good customer. There were also prank phone calls, all of which she attributed to a teenager who found it funny that we had the same last name as Spider-Man.", "rntLse": "neither", "propStatus": "Active", "bedrooms": "3", "totalBaths": "2.75", "latitude": "40.712968", "longitude": "-73.843206", "acres": "0.24", "sqFt": "2,760", "displayAddress": "y", "listingAgentID": "8675301", "listingOfficeID": "lmnop", "sample_mlsPtID": "1", "sample_mlsPhotoCount": "39", "parentPtID": "1", "detailsURL": "a000/5362657", "idxID": "a000", "idxPropType": "Residential", "idxStatus": "active", "viewCount": "2", "mediaData": [], "ohCount": "0", "vtCount": "0", "featured": "n", "image": { "0": { "url": "http://cdn.photos.ample_mls.com/az/20151113223546806109000000.jpg", "caption": "17596-20" }, "totalCount": "39" }, "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5362657/20-Ingram-Street-Forrest-Hills-NY-11375" }, "a000!%5358959": { "address": "177A Bleecker Street", "streetName": "Bleecker Street", "streetNumber": "177", "streetDirection": "N", "unitNumber": "A", "cityName": "Greenwich Village", "countyName": "New York", "state": "NY", "zipcode": "10012", "listingPrice": "$616,000,000", "listingID": "5358959", "remarksConcat": "Home to Dr. Stephen Vincent Strange(Doctor Strange in Marvel comics) and his faithful bodyguard and manservant Wong. Spider-Man often visits the Doctor for help when battling those with magic powers. Features: Wong's Storage Cellar, Strange's bedchambers, guest quarters, Wong's bedchamber, Study, Meditain Chamber, Library, Storage Area for Occult Artifacts.", "rntLse": "neither", "propStatus": "Active", "bedrooms": "2", "totalBaths": "2.75", "latitude": "40.729117", "longitude": "-74.000773", "acres": "0.31", "sqFt": "206800000000", "displayAddress": "y", "listingAgentID": "8675301", "listingOfficeID": "lmnop", "sample_mlsPtID": "1", "sample_mlsPhotoCount": "34", "parentPtID": "1", "detailsURL": "a000/5358959", "idxID": "a000", "idxPropType": "Residential", "idxStatus": "active", "viewCount": "6", "mediaData": [], "ohCount": "0", "vtCount": "0", "featured": "y", "image": { "0": { "url": "http://cdn.photos.sample_mls.com/az/20151105214013253867000000.jpg", "caption": "Front" }, "totalCount": "34" }, "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5358959/177A-Bleecker-Street-Greenwich-Village-NY-10012" } }

swift viewController

import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { //final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors" final let urlString = "https://api.idxbroker.com/clients/featured" @IBOutlet weak var tableView: UITableView! var nameArray = [String]() var dobArray = [String]() var imgURLArray = [String]() override func viewDidLoad() { super.viewDidLoad() self.downloadJsonWithTask() //self.downloadJsonWithURL() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /***********************************************************************************************/ func downloadJsonWithTask() { let url = NSURL(string: urlString) var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) /************** Get Users Accesy Key for API CALL *************************/ var key = String() let textFieldKeyConstant = "AccessKey" let defaults = UserDefaults.standard if let textFieldValue = defaults.string(forKey: textFieldKeyConstant) { key = textFieldValue } print(key) //accesskey debug /******************** End Get accessKey *************************************/ /******************** Add Headers required for API CALL *************************************/ downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") downloadTask.setValue(key, forHTTPHeaderField: "accesskey") downloadTask.setValue("json", forHTTPHeaderField: "outputtype") downloadTask.httpMethod = "GET" /******************** End Headers required for API CALL *************************************/ URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) print(jsonData ?? "Default") /******** Parse JSON **********/ /******** End Parse JSON **********/ /******** Reload table View **********/ OperationQueue.main.addOperation({ self.tableView.reloadData() }) }).resume() } /***********************************************************************************************/ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nameArray.count } /***********************************************************************************************/ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell cell.nameLabel.text = nameArray[indexPath.row] cell.dobLabel.text = dobArray[indexPath.row] let imgURL = NSURL(string: imgURLArray[indexPath.row]) if imgURL != nil { let data = NSData(contentsOf: (imgURL as URL?)!) cell.imgView.image = UIImage(data: data! as Data) } return cell } /****************************************************************/ ///for showing next detailed screen with the downloaded info func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController vc.imageString = imgURLArray[indexPath.row] vc.nameString = nameArray[indexPath.row] vc.dobString = dobArray[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } }

I am trying to parse this JSON that has a changing key for each object Im trying to find the best way to parse each object. I am very new to swift programming so any example code would be very helpful. I don't need to store all the values received just particular field such as address, streetName, image

JSON Input

{ "a000!%5362657": { "address": "20 Ingram Street", "streetName": "Ingram Street", "streetNumber": "20", "streetDirection": "N", "unitNumber": "", "cityName": "Forest Hills", "countyName": "New York", "state": "NY", "zipcode": "11375", "listingPrice": "$1,151,000", "listingID": "5362657", "remarksConcat": "From nytimes.com: In the comics, Peter Parker, the mild-mannered photojournalist who is Spider-Man's alter ego, grew up at 20 Ingram Street, a modest, two-story boarding house run by his Aunt May in the heart of Forest Hills Gardens. The address actually exists and is home to a family named Parker: Andrew and Suzanne Parker, who moved there in 1974, and their two daughters. In 1989, the family began receiving junk mail addressed to Peter Parker. We got tons of it, Mrs. Parker said yesterday. Star Trek magazines, a Discover Card in his name, and notices from them over the years calling him a good customer. There were also prank phone calls, all of which she attributed to a teenager who found it funny that we had the same last name as Spider-Man.", "rntLse": "neither", "propStatus": "Active", "bedrooms": "3", "totalBaths": "2.75", "latitude": "40.712968", "longitude": "-73.843206", "acres": "0.24", "sqFt": "2,760", "displayAddress": "y", "listingAgentID": "8675301", "listingOfficeID": "lmnop", "sample_mlsPtID": "1", "sample_mlsPhotoCount": "39", "parentPtID": "1", "detailsURL": "a000/5362657", "idxID": "a000", "idxPropType": "Residential", "idxStatus": "active", "viewCount": "2", "mediaData": [], "ohCount": "0", "vtCount": "0", "featured": "n", "image": { "0": { "url": "http://cdn.photos.ample_mls.com/az/20151113223546806109000000.jpg", "caption": "17596-20" }, "totalCount": "39" }, "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5362657/20-Ingram-Street-Forrest-Hills-NY-11375" }, "a000!%5358959": { "address": "177A Bleecker Street", "streetName": "Bleecker Street", "streetNumber": "177", "streetDirection": "N", "unitNumber": "A", "cityName": "Greenwich Village", "countyName": "New York", "state": "NY", "zipcode": "10012", "listingPrice": "$616,000,000", "listingID": "5358959", "remarksConcat": "Home to Dr. Stephen Vincent Strange(Doctor Strange in Marvel comics) and his faithful bodyguard and manservant Wong. Spider-Man often visits the Doctor for help when battling those with magic powers. Features: Wong's Storage Cellar, Strange's bedchambers, guest quarters, Wong's bedchamber, Study, Meditain Chamber, Library, Storage Area for Occult Artifacts.", "rntLse": "neither", "propStatus": "Active", "bedrooms": "2", "totalBaths": "2.75", "latitude": "40.729117", "longitude": "-74.000773", "acres": "0.31", "sqFt": "206800000000", "displayAddress": "y", "listingAgentID": "8675301", "listingOfficeID": "lmnop", "sample_mlsPtID": "1", "sample_mlsPhotoCount": "34", "parentPtID": "1", "detailsURL": "a000/5358959", "idxID": "a000", "idxPropType": "Residential", "idxStatus": "active", "viewCount": "6", "mediaData": [], "ohCount": "0", "vtCount": "0", "featured": "y", "image": { "0": { "url": "http://cdn.photos.sample_mls.com/az/20151105214013253867000000.jpg", "caption": "Front" }, "totalCount": "34" }, "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5358959/177A-Bleecker-Street-Greenwich-Village-NY-10012" } }

swift viewController

import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { //final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors" final let urlString = "https://api.idxbroker.com/clients/featured" @IBOutlet weak var tableView: UITableView! var nameArray = [String]() var dobArray = [String]() var imgURLArray = [String]() override func viewDidLoad() { super.viewDidLoad() self.downloadJsonWithTask() //self.downloadJsonWithURL() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /***********************************************************************************************/ func downloadJsonWithTask() { let url = NSURL(string: urlString) var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) /************** Get Users Accesy Key for API CALL *************************/ var key = String() let textFieldKeyConstant = "AccessKey" let defaults = UserDefaults.standard if let textFieldValue = defaults.string(forKey: textFieldKeyConstant) { key = textFieldValue } print(key) //accesskey debug /******************** End Get accessKey *************************************/ /******************** Add Headers required for API CALL *************************************/ downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") downloadTask.setValue(key, forHTTPHeaderField: "accesskey") downloadTask.setValue("json", forHTTPHeaderField: "outputtype") downloadTask.httpMethod = "GET" /******************** End Headers required for API CALL *************************************/ URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) print(jsonData ?? "Default") /******** Parse JSON **********/ /******** End Parse JSON **********/ /******** Reload table View **********/ OperationQueue.main.addOperation({ self.tableView.reloadData() }) }).resume() } /***********************************************************************************************/ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nameArray.count } /***********************************************************************************************/ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell cell.nameLabel.text = nameArray[indexPath.row] cell.dobLabel.text = dobArray[indexPath.row] let imgURL = NSURL(string: imgURLArray[indexPath.row]) if imgURL != nil { let data = NSData(contentsOf: (imgURL as URL?)!) cell.imgView.image = UIImage(data: data! as Data) } return cell } /****************************************************************/ ///for showing next detailed screen with the downloaded info func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController vc.imageString = imgURLArray[indexPath.row] vc.nameString = nameArray[indexPath.row] vc.dobString = dobArray[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } }

最满意答案

对于swift3 [String:Any]它是一个字典与密钥有字符串任何类型的Swift,它描述了任何类型的值

do { let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any] print(parsedData) } catch let error as NSError { print(error) }

例如 :

if let info = parsedData["a000!%5362657"] as? [String : String]{ if let address = info["address"] { print(address) } }

在Swift苹果博客https://developer.apple.com/swift/blog/?id=37中使用JSON

for swift3 [String:Any] it is a Dictionary with key has String and Any type in Swift, which describes a value of any type

do { let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any] print(parsedData) } catch let error as NSError { print(error) }

For example :

if let info = parsedData["a000!%5362657"] as? [String : String]{ if let address = info["address"] { print(address) } }

Working with JSON in Swift apple blog https://developer.apple.com/swift/blog/?id=37

更多推荐

本文发布于:2023-08-04 16:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417665.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   Swift   JSON   dynamic   parsing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!