Swift - JSON 파싱

Programming/Swift 2017.06.17 12:43 Posted by 파란크리스마스

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)
        }
    }
저작자 표시
신고


 

티스토리 툴바