티스토리 뷰
728x90
json 파싱
let jsonString = "{ \"name\":\"test\", \"age\":30 }" if let data = jsonString.data(using: .utf8) { do { if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { print(json["name"] ?? "") print(json["age"] ?? 0) } } catch { print("JSON 파싱 에러") } }
원격호출 json 파싱
let urlString = "http://115.68.183.178:2029/hoppin/movies?order=releasedateasc&count=10&page=1&version=1&genreId=" guard let url = URL(string: urlString) else { return } let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in guard let data = data, let httpRes = response as? HTTPURLResponse, httpRes.statusCode == 200 else { return } if let error = error { print(error.localizedDescription) return; } do { if let jsonDic = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { print(jsonDic) guard let totalInfo = jsonDic["hoppin"] as? [String : AnyObject], let totalCount = totalInfo["totalCount"] as? String, let movies = totalInfo["movies"] as? [String :AnyObject], let movieArray = movies["movie"] as? [[String:AnyObject]] else {return} print(totalCount) print(movies) for info in movieArray { print(info["title"] ?? "") print(info["thumbnailImage"] ?? "") let movieInfo = MovieInfo(title : info["title"] as? String, thumbnailUrl : info["thumbnailImage"] as? String, genre : info["genreNames"] as? String, ratingAverage : info["ratingAverage"] as? String) self.movieArray.append(movieInfo) } } } catch { print("JSON 파상 에러") } print("JSON 파싱 완료") // 메일 쓰레드에서 화면 갱신 DispatchQueue.main.async { self.tvMovie.reloadData() } }) print("JSON 파싱 시작") task.resume()
json 파싱 함수로 구현
func parseJSONString(jsonString : String) -> [String:AnyObject]? { guard let data = jsonString.data(using: .utf8) else { return nil } do { if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] { print(json); return json } } catch { print("JSON 파싱 에러") } return nil } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let jsonString = "{ \"name\":\"test\", \"age\":30 }" if let jsonDic = self.parseJSONString(jsonString: jsonString) { print(jsonDic["name"] ?? "") print(jsonDic["age"] ?? 0) } }
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- MySQL
- Linux
- SAS
- Java
- Spring MVC
- 지스타2007
- 전예희
- sas2009
- oracle
- ubuntu
- NDK
- Mac
- 튜닝쇼 2008
- BPI-M4
- 레이싱모델 익스트림 포토 페스티벌
- flex
- koba2010
- 서울오토살롱
- Spring
- 일본여행
- Delphi
- JavaScript
- 송주경
- 동경
- KOBA
- ble
- ffmpeg
- Xcode
- Delphi Tip
- android
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함