로그인 기능 (POST 메소드)을 작성하려고하는데 결과적으로 사용자 세부 사항 및 기타 몇 가지 세부 사항이있는 JSON이 생성됩니다. POST 호출의 결과에서 사용해야하는 모든 필드가있는 클래스를 만들었습니다. 하지만 클래스의 객체에 json을 디시 리얼 라이징하는 문제에 직면하고 있습니다. 어떤 사람이 이것으로 나를 도울 수 있습니까?신속한 객체에 사전 (JSON)을 비 직렬화합니다.
내 코드 (. 내가 SO에 비슷한 질문을 본 및 솔루션을 사용하여 해결 시도 나는 var UserDetails = UserDetails(json:jsonString)
사용하여 신속 객체에 다음 문자열로 JSON 변환 및 시도) :
class UserDetails {
let token:String
let agent_id: Int
let user_id:Int
let company_id:Int
let affliate_Id:Int
let role_id:Int
let username: String
let surname:String
let lastname:String
init(token:String,agent_id: Int,user_id:Int,company_id:Int,affliate_Id:Int,role_id:Int,username: String,surname:String,lastname:String) {
self.token = token;
self.agent_id = agent_id;
self.user_id = user_id;
self.company_id = company_id;
self.affliate_Id = affliate_Id;
self.role_id = role_id;
self.username = username;
self.surname = surname;
self.lastname = lastname;
} }
내 컨트롤러 클래스 :
let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
NSLog("Login SUCCESS");
let prefs:UserDefaults = UserDefaults.standard
prefs.set(username, forKey: "USERNAME")
prefs.set(udid, forKey: "UDID")
prefs.synchronize()
print("Response: \(json)")
//var jsonString = NSString(data: json, encoding: String.Encoding.utf8)! as String
//when I tried to do the above statement, an error is thrown. Cannot convert value of type NSDictionary to expected argument type Data
//var person:UserDetails = UserDetails(json: jsonString)
self.dismiss(animated: true, completion: nil)
} else {
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
JSON 응답 :
{
"user": {
"token": "ABCDEFGHI",
"agent_id": 0,
"user_id": 151,
"company_id": 1,
"affiliate_Id": 0,
"role_id": 1,
"username": "testman1",
"surname": "Test",
"lastname": "man",
},
"menu": [
{ .....
누가이 문제를 해결할 수 있습니까? 티아
당신이 유형[String: Any]
의 단일 매개 변수로
UserDetails
당신의 init 메소드를 정의하는 경우도 타자 스위프트 기본
Dictionary
대신
NSDictionary
의 사용에 필요한 모든의
여기에 귀하의 json 응답을 추가하십시오. –
@NiravD는 JSON 응답으로 질문을 업데이트했습니다. 제발 봐주세요 – ASN
당신은 파운데이션 클래스 (NSDictionary 등)를 사용하지 말고 스위프트 타입을 사용해야합니다. 그래서,'if json = JSONSerialization.jsonObject를 사용하면 (데이터 :, 옵션 : [])? [String : Any]' – Paulw11