다음과 같은 서버에서 json 응답을 받았습니다.
"{\"userID\":\"dkjagfhaghdalgalg\"}"
이 사용자 ID를 얻으려고합니다.
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) -> Void in
if let unwrappedData = data {
do {
let userIDDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print("userIDDictionary:\(userIDDictionary)")
//let userID:String = userIDDictionary["userID"] as! String
//print("userID:\(userID)")
print("data:\(data)")
print("response:\(response)")
print("error:\(error)")
} catch {
print("Failed to get userID: \(error)")
}
}
}
그러나 응답은
사용자 ID를 가져 오지 못했습니다. 오류 도메인 = NSCocoaErrorDomain Code = 3840 "JSON 텍스트가 배열 또는 개체로 시작되지 않았으며 조각을 허용하는 옵션이 설정되지 않았습니다. UserInfo = {NSDebugDescription = JSON 텍스트가 배열 또는 개체로 시작되지 않았으며 조각을 허용하지 않는 옵션이 없습니다. 세트.}".
그런 json 응답으로 userID를 얻는 방법은 무엇입니까?
업데이트 : 나는 anyobject를 얻으려고 시도했지만 여전히 json 문자열을 사전으로 변경하지 못했습니다.
let bodyStr = "test={ \"email\" : \"\(username)\", \"password\" : \"\(password)\" }"
let myURL = NSURL(string: Constant.getSignInEmail())!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)!
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) -> Void in
if let unwrappedData = data {
do {
let json:AnyObject! = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! AnyObject
print("json:\(json)")
//let userID:String = userIDDictionary["userID"] as! String
//print("userID:\(userID)")
} catch {
print("Failed to get userID: \(error)")
}
}
}
json 읽기 옵션에서 NSJSONReadingOptions.AllowFragments를 사용해보십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다