모바일/iOS

Swift2 - String to JSON Object

늘근이 2016. 6. 8. 05:35

Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'



JSON의 제일 상위가 []로 감싸져있을때는 Array타입이며 {}는 Dictionary 타입이다. 만약, 최상위가 []로 감싸져있다면 다음과 같이 NSMutableArray로 변환해야하는걸로 보인다.


let data = responseString?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        

        do {

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSMutableArray

            print("\(json)")

            

        } catch let error as NSError {

            print("Failed to load: \(error.localizedDescription)"   )

        }



NSMutableArray 대신 NSDictionary를 넣거나 [String : AnyObject] 를 넣는다면 빨간색 문구와 같은 에러가 보인다.

'모바일 > iOS' 카테고리의 다른 글

[Swift2] JSON -> SwiftObject  (0) 2016.07.10
Swift2 - CallBack 예제  (0) 2016.07.10
[링크] Swift - SQLite  (0) 2016.06.07
Swift2 - NSData to ByteArray (UInt8)  (0) 2016.06.06
Swift2 - Using faceAPI and sending binary data to server  (0) 2016.06.06