当前位置: 首页 > 知识库问答 >
问题:

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

方茂
2023-03-14

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

Error Domain=NSCoaErrorDomain Code=3840"字符0周围的值无效。"UserInfo={NSDebugDescription=字符0周围的值无效。}反序列化JSON时出错:Error Domain=NSCoaErrorDomain Code=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个答案

姜楷
2023-03-14

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

只需做一次:

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()
}
裴星洲
2023-03-14

尝试像这样序列化 json

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

并删除另一种序列化方式,确保从服务器返回的数据是json可序列化的,方法是处理服务器家伙的伪返回,并在任何站点验证它为json

上官高畅
2023-03-14

它不起作用的原因是,完全调用您所拥有的内容会返回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 Code = 3840“JSON文本没有以数组或对象开头,并且未设置允许片段的选项。”UserInfo = { NSDebugDescription = JSON文本未以数组或对象开头,并且未设置允许片段的选项。}

首先,请确保您实际上没有从 API 收到错误响应,您是:

<NSHTTPURLResponse: 0x6040002217c0> { URL: http://ash.no-ip.biz/MyService.asmx/A_loginDetailTailorApp_IOS } { Status Code: 500, Headers {
 类似资料:
  • 使用阿拉莫菲尔。post api,在postman中而不是在我的代码中提供数据的api。在代码下面发帖,请指导我在这里做错了什么: 错误:失败:responseSerializationFailed(alamo fire。AFError . responseserializationfailure reason . jsonserializationfailed(Error Domain = NS

  • 我正在尝试将图像上载到服务器,它工作正常,但偶尔我会在下面的代码中收到try语句错误。这就是错误所说的 致命错误:“try!”表达式意外引发错误:错误域 = NSCocoa错误域代码 = 3840 “字符 0 周围的无效值”。用户信息={NSDebug 说明= 字符 0.} 周围的无效值:文件/库/缓存/com.apple.xbs/源/swiftlang_PONDEROSA/swiftlang_P

  • 问题内容: 这是我对Alamofire的要求,对于某些要求它有时可以工作,但有时我会得到: 我已经读到这可能是由于无效的JSON引起的,但是响应是我在JSON验证程序中验证为有效的静态JSON字符串。它确实包含åö字符和一些HTML。 为什么有时会出现此错误? 问题答案: 我也面临同样的问题。我尝试而不是,它的工作。我猜这是与一起使用时的错误。

  • 我收到此错误 错误域 = NSCocoa错误域代码 = 3840 “字符 746 周围的无效转义序列”。用户信息={NS诊断描述=字符 746 周围的无效转义序列。 下面是我解析JSON的代码: 使用此代码,我可以在其他API中获得响应对象。但在我的API中包含HTML标记。 我的问题是我得到的是JSON字符串,但它不是用JSON解析的。对于此API,我遇到错误 “错误域=NSCocoaError

  • 我正在尝试使用xcode中的Switf 4使用rest Web服务,这是我的代码: 这是我在xcode控制台中的回答: Linea 50:Error Domain=NSCocoaErrorDomain Code=3840“字符0周围的值无效。”UserInfo={NSDebugDescription=字符0周围无效的值。}Linea 52:可选(“|{\”login\“:\”true\“}”) 这

  • 我使用AFNetworking在iOS中使用post方法从服务器获取数据,但我得到的状态代码是200 OK,但在AFNetworking中,它有Failure methods和下面的错误显示,我也在google上搜索过,我也尝试过基于结果的搜索,但显示的错误相同。 等待您的回复。 状态代码 :- 错误:-Error Domain=NSCocoaErrorDomain Code=3840"操作无法完