why is string response from server changing when I am using alamofire in ios app?

≯℡__Kan透↙ 提交于 2019-12-23 06:58:25

问题


I am trying to retrieve a string from server using alamofire in an ios app but the problem is that the response is changing as it is prefixing ever entity with "\" character. here is my code:

func getInformation()
    {
        self.activityIndicator.startAnimating()
        let parameters: Parameters = ["SchoolCode": "TCenYrhWUQH7kKLVZ1FQgQ==", "FacultyInfoCode":"cFl9ivLKKKk5PgH4tbi/Gg=="]
        Alamofire.request("http://epunjabschool.gov.in/webservice/staffwebservice.asmx/StaffDetails", method: .post, parameters: parameters).responseString{ response in
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            self.activityIndicator.stopAnimating()
            if let JsON = response.result.value {
                var string = JsON
                if let idx = string.lastIndex(of:"[") {
                      var index1=idx+1
                    var index2 = string.lastIndex(of:"]")!-1
                    var substring = string.substring(from:index1,to:index2)
                        if let dataFromString = substring.data(using: .utf8, allowLossyConversion: false) {
                            let json = JSON(data: dataFromString)
                      //      for i in 0..<json.count
                         //   {
                                var js=json[0]
                                if(self.defaults.string(forKey: "status") == "hr")
                                {
                                     self.district.text=js["Name"].stringValue
                                     self.school.text=js["UserMaster_DisplayName"].stringValue
                                }
                                else
                                {
                                   self.district.text=js["Faculty_Name"].stringValue
                                    self.school.text="dfjdnfj"

                                }
                           // }
                        }

                    }
                }

            }
        }

here is the response which i am getting when running the same service from broswer:

<string xmlns="http://tempuri.org/">
[{"FacultyInfo_Code":"107406","Faculty_Name":"Vipul bansal","Father_Name":"Vijay kumar","DOB":"21-Sep-1986","Gender":"Male","CasteCategory_Name":"GENERAL","Religion_Name":"HINDU","MaritalStatus_Name":"UnMarried","Disability":"No Disability","Qualification_Acad":"+2","Qualification_Prof":"MSC(IT)","ComputerTypingKnowledge_Name":"Both","Cur_Address":"sikkhan wala road, channy street, house no.2, kotkapura, FARIDKOT, Punjab","Per_Address":"sikkhan wala road, channy street, house no.2, kotkapura, S.A.S. NAGAR, Punjab","Disatance":"27.00","MobileNo":"8427010890","EmailID":"vipulbansal59@yahoo.in"}]~[{"FacultyInfo_Code":"107406","Faculty_Name":"Vipul bansal","Father_Name":"Vijay kumar","DOB":"21-Sep-1986","Gender":"Male","ServiceType":"Regular","StaffType":"Teaching","AppointmentUnder":"PICTES","Current_DesignationName":"Computer Faculty","Subject_Taught":"COMPUTER SCIENCE","DateOfJoining":"18-Sep-2009","Joining_Present_Desination":"29-Oct-2010","DISTRICT_CODE":"5","DISTRICT_NAME":"FARIDKOT","School_Name":"GHS DHURKOT","EDU_BLOCK_NAME":"FARIDKOT-03","udise_code":"03130103102","RecordType":"S","Mobile_No":"8427010890","Email_Id":"vipulbansal59@yahoo.in"}]
</string>

here is the reponse from alamofire:

"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://tempuri.org/\">[{\"FacultyInfo_Code\":\"107406\",\"Faculty_Name\":\"Vipul bansal\",\"Father_Name\":\"Vijay kumar\",\"DOB\":\"21-Sep-1986\",\"Gender\":\"Male\",\"CasteCategory_Name\":\"GENERAL\",\"Religion_Name\":\"HINDU\",\"MaritalStatus_Name\":\"UnMarried\",\"Disability\":\"No Disability\",\"Qualification_Acad\":\"+2\",\"Qualification_Prof\":\"MSC(IT)\",\"ComputerTypingKnowledge_Name\":\"Both\",\"Cur_Address\":\"sikkhan wala road, channy street, house no.2, kotkapura, FARIDKOT, Punjab\",\"Per_Address\":\"sikkhan wala road, channy street, house no.2, kotkapura, S.A.S. NAGAR, Punjab\",\"Disatance\":\"27.00\",\"MobileNo\":\"8427010890\",\"EmailID\":\"vipulbansal59@yahoo.in\"}]~[{\"FacultyInfo_Code\":\"107406\",\"Faculty_Name\":\"Vipul bansal\",\"Father_Name\":\"Vijay kumar\",\"DOB\":\"21-Sep-1986\",\"Gender\":\"Male\",\"ServiceType\":\"Regular\",\"StaffType\":\"Teaching\",\"AppointmentUnder\":\"PICTES\",\"Current_DesignationName\":\"Computer Faculty\",\"Subject_Taught\":\"COMPUTER SCIENCE\",\"DateOfJoining\":\"18-Sep-2009\",\"Joining_Present_Desination\":\"29-Oct-"...    

As it can be seen, the problem is the "\" extra character in the alamofire response making it impossible for me to parse the json data. Why is the data changing in alamofire response?


回答1:


Alamofire is not changing the data, this is just the way the console prints it out. The easiest way to handle this would be to simply couple ObjectMapper along with Alamofire to parse this response. OR you could use the following :

func getInformation()
{
    self.activityIndicator.startAnimating()
    let parameters: Parameters = ["SchoolCode": "TCenYrhWUQH7kKLVZ1FQgQ==", "FacultyInfoCode":"cFl9ivLKKKk5PgH4tbi/Gg=="]
    Alamofire.request("http://epunjabschool.gov.in/webservice/staffwebservice.asmx/StaffDetails", method: .post, parameters: parameters, encoding: .JSON).responseJSON{ response in

switch response.result {
case .success:
    let json = response.result.value
case .failure(let error):
    print(error)
}
}



回答2:


This is JSON formatted String:

{\"FacultyInfo_Code\":\"107406\",\"Faculty_Name\":\"Vipul bansal\",\"Father_Name\":\"Vijay kumar\",\"DOB\":\"21-Sep-1986\",\"Gender\":\"Male\",\"CasteCategory_Name\":\"GENERAL\",\"Religion_Name\":\"HINDU\",\"MaritalStatus_Name\":\"UnMarried\",\"Disability\":\"No Disability\",\"Qualification_Acad\":\"+2\",\"Qualification_Prof\":\"MSC(IT)\",\"ComputerTypingKnowledge_Name\":\"Both\",\"Cur_Address\":\"sikkhan wala road, channy street, house no.2, kotkapura, FARIDKOT, Punjab\",\"Per_Address\":\"sikkhan wala road, channy street, house no.2, kotkapura, S.A.S. NAGAR, Punjab\",\"Disatance\":\"27.00\",\"MobileNo\":\"8427010890\",\"EmailID\":\"vipulbansal59@yahoo.in\"}]~[{\"FacultyInfo_Code\":\"107406\",\"Faculty_Name\":\"Vipul bansal\",\"Father_Name\":\"Vijay kumar\",\"DOB\":\"21-Sep-1986\",\"Gender\":\"Male\",\"ServiceType\":\"Regular\",\"StaffType\":\"Teaching\",\"AppointmentUnder\":\"PICTES\",\"Current_DesignationName\":\"Computer Faculty\",\"Subject_Taught\":\"COMPUTER SCIENCE\",\"DateOfJoining\":\"18-Sep-2009\"....

If you will parse it then you will be able to see it without \"

Parse it using NSJSONSerialization:

func getInformation()
    {
        self.activityIndicator.startAnimating()
        let parameters: Parameters = ["SchoolCode": "TCenYrhWUQH7kKLVZ1FQgQ==", "FacultyInfoCode":"cFl9ivLKKKk5PgH4tbi/Gg=="]
        Alamofire.request("http://epunjabschool.gov.in/webservice/staffwebservice.asmx/StaffDetails", method: .post, parameters: parameters).responseString{ response in
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            self.activityIndicator.stopAnimating()
            //UPdated Code
            do {
                let responseObject = try     NSJSONSerialization.JSONObjectWithData(response.data, options: []) as!  [String:AnyObject]

//Use responseObject as NSdictonary to get your data

    } catch let error as NSError {
 print("error: \(error.localizedDescription)")
}

            if let JsON = response.result.value {
                var string = JsON
                if let idx = string.lastIndex(of:"[") {
                      var index1=idx+1
                    var index2 = string.lastIndex(of:"]")!-1
                    var substring = string.substring(from:index1,to:index2)
                        if let dataFromString = substring.data(using: .utf8, allowLossyConversion: false) {
                            let json = JSON(data: dataFromString)
                      //      for i in 0..<json.count
                         //   {
                                var js=json[0]
                                if(self.defaults.string(forKey: "status") == "hr")
                                {
                                     self.district.text=js["Name"].stringValue
                                     self.school.text=js["UserMaster_DisplayName"].stringValue
                                }
                                else
                                {
                                   self.district.text=js["Faculty_Name"].stringValue
                                    self.school.text="dfjdnfj"

                                }
                           // }
                        }

                    }
                }

            }
        }


来源:https://stackoverflow.com/questions/41355457/why-is-string-response-from-server-changing-when-i-am-using-alamofire-in-ios-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!