0
votes

I'm new to iOS. I'm getting this error:

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.} Error deserializing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

I google it but I didn't get anything

Here is my JSON:

{
    "LoginDetails": [{
        "UserId": 5,
        "Type": "Sales",
        "Name": "Andy",
        "EmailId": "[email protected]",
        "MobileNo": "60863407"
    }]
}

Here is my code. Did I do anything wrong?

 func CheckLoginDrails() {   
     let parameters = ["[email protected]&Password=ANDY1969&DepartmentId=1"]
    guard let url = URL(string:"http://ash.no-ip.biz/MyService.asmx/A_loginDetailTailorApp_IOS")else{
        return
    }
    var request = URLRequest(url:url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpbody = try?JSONSerialization.data(withJSONObject: parameters, options: []) else {
        return
    }
    request.httpBody = httpbody
    let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do{
                let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
                print(json)
            }catch{
                print(error)
            }
        }
        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let blogs = json["LoginDetails"] as? [[String: Any]] {
                for blog in blogs {

                    let UserId = blog["UserId"] as? String
                    let name = blog["Name"] as? String
                    let email = blog["EmailId"] as? String
                    let Type = blog["Type"] as? String
                    let MobileNo = blog["MobileNo"] as? String

                    print("UserID: ",UserId)
                    print("Name: ",name)
                    print("Email",email)
                    print("Type: ",Type)
                    print("MobileNo: ",MobileNo)
                }
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }
    }
    session.resume()
}
3
Why are you attempting to deserialize the resulting JSON twice? - rmaddy
I don't know actually, I google it n did something like this. so what I need to do?@maddy - Pratik

3 Answers

0
votes

The reason it's not working is because calling exactly what you have is returning a 500 error and the data looks like this:

("<!DOCTYPE html>\r\n<html>\r\n    <head>\r\n        <title>Only Web services with a [ScriptService] attribute on the class definition can be called from script.</title>\r\n        <meta name=\"viewport\" content=\"width=device-width\" />\r\n        <style>\r\n         body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n         p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n         b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n         H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n         H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n         pre {font-family:\"Consolas\",\"Lucida Console\",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}\r\n         .marker {font-weight: bold; color: black;text-decoration: none;}\r\n         .version {color: gray;}\r\n         .error {margin-bottom: 10px;}\r\n         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n         @media screen and (max-width: 639px) {\r\n          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }\r\n         }\r\n         @media screen and (max-width: 479px) {\r\n          pre { width: 280px; }\r\n         }\r\n        </style>\r\n    </head>\r\n\r\n    <body bgcolor=\"white\">\r\n\r\n            <span><H1>Server Error in \'/\' Application.<hr width=100% size=1 color=silver></H1>\r\n\r\n            <h2> <i>Only Web services with a [ScriptService] attribute on the class definition can be called from script.</i> </h2></span>\r\n\r\n            <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.\r\n\r\n            <br><br>\r\n\r\n            <b> Exception Details: </b>System.InvalidOperationException: Only Web services with a [ScriptService] attribute on the class definition can be called from script.<br><br>\r\n\r\n            <b>Source Error:</b> <br><br>\r\n\r\n            <table width=100% bgcolor=\"#ffffcc\">\r\n               <tr>\r\n                  <td>\r\n                      <code>\r\n\r\nAn unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>\r\n\r\n                  </td>\r\n               </tr>\r\n            </table>\r\n\r\n            <br>\r\n\r\n            <b>Stack Trace:</b> <br><br>\r\n\r\n            <table width=100% bgcolor=\"#ffffcc\">\r\n               <tr>\r\n                  <td>\r\n                      <code><pre>\r\n\r\n[InvalidOperationException: Only Web services with a [ScriptService] attribute on the class definition can be called from script.]\r\n   System.Web.Script.Services.WebServiceData..ctor(Type type, Boolean pageMethods) +619597\r\n   System.Web.Script.Services.WebServiceData.GetWebServiceData(HttpContext context, String virtualPath, Boolean failIfNoData, Boolean pageMethods, Boolean inlineScript) +286\r\n   System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context) +109\r\n   System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +63\r\n   System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47\r\n   System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +226\r\n   System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +145\r\n   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155\r\n</pre></code>\r\n\r\n                  </td>\r\n               </tr>\r\n            </table>\r\n\r\n            <br>\r\n\r\n            <hr width=100% size=1 color=silver>\r\n\r\n            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0\r\n\r\n            </font>\r\n\r\n    </body>\r\n</html>\r\n<!-- \r\n[InvalidOperationException]: Only Web services with a [ScriptService] attribute on the class definition can be called from script.\r\n   at System.Web.Script.Services.WebServiceData..ctor(Type type, Boolean pageMethods)\r\n   at System.Web.Script.Services.WebServiceData.GetWebServiceData(HttpContext context, String virtualPath, Boolean failIfNoData, Boolean pageMethods, Boolean inlineScript)\r\n   at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)\r\n   at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n   at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n   at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)\r\n   at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)\r\n--><!-- \r\nThis error page might contain sensitive information because ASP.NET is configured to show verbose error messages using &lt;customErrors mode=\"Off\"/&gt;. Consider using &lt;customErrors mode=\"On\"/&gt; or &lt;customErrors mode=\"RemoteOnly\"/&gt; in production environments.-->")

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

First, make sure that you are actually not getting an error response from the API, which you are:

<NSHTTPURLResponse: 0x6040002217c0> { URL: http://ash.no-ip.biz/MyService.asmx/A_loginDetailTailorApp_IOS } { Status Code: 500, Headers {
0
votes

Try serialize json like this

 var responseDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]

and remove the other serialize way and ensure that data returned from server is json serializable by coping dummy return from server guy and validate it as json in any site

0
votes

You are attempting to deserialize the response twice and the second time you are trying to use the data from the first time.

Just do it once:

func CheckLoginDrails() {   
    let parameters = ["[email protected]&Password=ANDY1969&DepartmentId=1"]
    guard let url = URL(string:"http://ash.no-ip.biz/MyService.asmx/A_loginDetailTailorApp_IOS")else{
        return
    }

    var request = URLRequest(url:url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpbody = try?JSONSerialization.data(withJSONObject: parameters, options: []) else {
        return
    }

    request.httpBody = httpbody
    let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do{
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any], let blogs = json["LoginDetails"] as? [[String: Any]] {
                    for blog in blogs {
                        let UserId = blog["UserId"] as? String
                        let name = blog["Name"] as? String
                        let email = blog["EmailId"] as? String
                        let Type = blog["Type"] as? String
                        let MobileNo = blog["MobileNo"] as? String

                        print("UserID: ",UserId)
                        print("Name: ",name)
                        print("Email",email)
                        print("Type: ",Type)
                        print("MobileNo: ",MobileNo)
                    }
                } else {
                    print("JSON wasn't a dictionary containing LoginDetails")
                }
            }catch{
                print(error)
                print("Actual result: \(String(data: data, encoding: .utf8))")
            }
        }
    }
    session.resume()
}