Строка JSON в словарь в Swift 4 - PullRequest
0 голосов
/ 17 декабря 2018

Я получаю ответ от сервера в формате JSON в этом формате.

{"ResponseCode":1,"StudentDetails":[{"Student_ID":1,"Student_SchoolID":1,"Student_BranchID":1,"Student_ClassID":1,"Student_FirstName":"1","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"19/03/2017","Student_EnrollmentNo":"1","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/IMG100710620180809104233860.JPG","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":278324,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Ganu now","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":267971,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":4894,"Student_FirstName":"Poonam Dillo saii","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"2211","Class_Name":"Nursery A","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/FB_IMG_145451330612110622062018203844.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":272466,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Poonam ganu","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":273560,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14564,"Student_FirstName":"Ganesh kumar saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"Primary","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":133262,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":5065,"Student_FirstName":"Lavish saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"04/02/2018","Student_EnrollmentNo":"09EEBMIT29","Class_Name":"KG ICA","Student_Password":"123456","Student_PrimaryEmailID":"ganeshsaini01@gmail.com","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/download110682201811024710015409877121411061541069294120.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}],"StudentMenusCount":[{"CountValue":0,"StudentId":0,"CountFor":"StudyPlanner","DatabaseID":0,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}]}

Теперь я получаю ответ в формате JSON String.Мне нужно преобразовать его в словарь.Я использую этот код для синтаксического анализа json.

let myJson = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as Any

if myJson is String {
    print(myJson) // Printing Here as myJson is String.
}

Если я пишу в коде выше, как:

let myJson = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]

Это жалуется на плохого JSON, чемЛюбая идея о том, как преобразовать строку JSON в словарь здесь?

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

Это способ сделать это, но вы должны сказать, в чем ошибка:

 if let data = Data(result.utf8) {
  do {
     let myJson = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]

 } catch let error {
        print(error)
 }
}
0 голосов
/ 17 декабря 2018

Я думаю, что JSON в порядке, однако способ анализа JSON - нет.

Я попытался с этим кодом, и результат ожидается.

let response = """
{"ResponseCode":1,"StudentDetails":[{"Student_ID":1,"Student_SchoolID":1,"Student_BranchID":1,"Student_ClassID":1,"Student_FirstName":"1","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"19/03/2017","Student_EnrollmentNo":"1","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/IMG100710620180809104233860.JPG","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":278324,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Ganu now","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":267971,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":4894,"Student_FirstName":"Poonam Dillo saii","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"2211","Class_Name":"Nursery A","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/FB_IMG_145451330612110622062018203844.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":272466,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Poonam ganu","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":273560,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14564,"Student_FirstName":"Ganesh kumar saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"Primary","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":133262,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":5065,"Student_FirstName":"Lavish saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"04/02/2018","Student_EnrollmentNo":"09EEBMIT29","Class_Name":"KG ICA","Student_Password":"123456","Student_PrimaryEmailID":"ganeshsaini01@gmail.com","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/download110682201811024710015409877121411061541069294120.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}],"StudentMenusCount":[{"CountValue":0,"StudentId":0,"CountFor":"StudyPlanner","DatabaseID":0,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}]}
"""

if let data = response.data(using: .utf8) {
  let myJson = try JSONSerialization.jsonObject(with: data, 
                                                options: JSONSerialization.ReadingOptions.allowFragments) as Any

  if myJson is String {
    print(myJson) // <-- This will not print anything as myJson is not a string
  }

  if let dict = myJson as? [String: Any] {
    print(dict.keys) // <-- This will print a list of keys 
  }
}
...