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

Posted

技术标签:

【中文标题】错误域 = NSCocoaErrorDomain 代码 = 3840 “字符周围的值无效【英文标题】:Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 【发布时间】:2018-06-17 17:55:36 【问题描述】:

我是 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()

【问题讨论】:

您为什么要尝试对生成的 JSON 进行两次反序列化? 我实际上不知道,我用谷歌搜索它 n 做了这样的事情。那我需要做什么?@maddy 【参考方案1】:

它不工作的原因是因为调用你所拥有的东西会返回一个 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“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。” UserInfo=NSDebugDescription=JSON 文本不以数组或对象开头,并且允许未设置片段的选项。

首先,确保您实际上没有收到来自 API 的错误响应:

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

【讨论】:

是的,我检查日志显示此错误。但是当我从网上检查时,它工作正常。这是链接ash.no-ip.biz/MyService.asmx?op=A_loginDetailTailorApp_IOS Username=andy@ashtailor.com Password=ANDY1969 DepartmentId=1 现在,我需要做什么?【参考方案2】:

尝试像这样序列化 json

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

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

【讨论】:

【参考方案3】:

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

只做一次:

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()

【讨论】:

不,它现在不起作用我收到此错误,错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。” UserInfo=NSDebugDescription=JSON 文本不以数组或对象开头,并且允许未设置片段的选项。 那么你从服务器获取的数据不是 JSON。 查看我更新的答案,如果接收到的数据不是有效的 JSON,它将尝试将其打印为字符串。 不工作,打印 print("Actual result: (String(data: data, encoding: .utf8))" 你忘了反斜杠吗?

以上是关于错误域 = NSCocoaErrorDomain 代码 = 3840 “字符周围的值无效的主要内容,如果未能解决你的问题,请参考以下文章

Json 错误:错误域 = NSCocoaErrorDomain 代码 = 3840“无值”。 UserInfo=NSDebugDescription=无值。

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

iOS swift 中的错误域 = NSCocoaErrorDomain 代码 = 3840?

iOS:- 错误:无法创建存储目录。错误域 = NSCocoaErrorDomain 代码 = 512

如何修复“错误域 = NSCocoaErrorDomain 代码 = 3840”无价值。“UserInfo = NSDebugDescription = 无价值。”

错误域=NSCocoaErrorDomain 代码=3840 JSONObject