错误域= NSCocoaErrorDomain代码= 3840"字符周围的值无效

时间:2018-01-08 17:57:50

标签: ios json swift

我是iOS新手。我收到此错误:

  

错误域= NSCocoaErrorDomain代码= 3840"字符0周围的值无效。" UserInfo = {NSDebugDescription =字符0周围的值无效}   反序列化JSON时出错:错误域= NSCocoaErrorDomain代码= 3840" JSON文本不以数组或对象和选项开头,以允许未设置片段。" UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

我谷歌但我没有得到任何东西

这是我的JSON:

{
    "LoginDetails": [{
        "UserId": 5,
        "Type": "Sales",
        "Name": "Andy",
        "EmailId": "andy@ashtailor.com",
        "MobileNo": "60863407"
    }]
}

这是我的代码。我做错了吗?

 func CheckLoginDrails() {   
     let parameters = ["Username=andy@ashtailor.com&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 个答案:

答案 0 :(得分:0)

您尝试将响应反序列化两次,第二次尝试使用数据时。

只做一次:

func CheckLoginDrails() {   
    let parameters = ["Username=andy@ashtailor.com&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()
}

答案 1 :(得分:0)

尝试像这样序列化json

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

并删除其他序列化方式并确保从服务器返回的数据是json可序列化的,通过从服务器人处理虚拟返回并在任何站点中将其验证为json

答案 2 :(得分:0)

它无法正常工作的原因是因为正确调用所返回的500错误而且数据如下所示:

("<!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.-->")

错误域= NSCocoaErrorDomain代码= 3840&#34; JSON文本不是以数组或对象开头,而是选项允许未设置片段。&#34; UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

首先,确保您实际上没有从API获得错误响应,您是:

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