代码之家  ›  专栏  ›  技术社区  ›  raginggoat

afnetworking从响应中修剪字符

  •  0
  • raginggoat  · 技术社区  · 6 年前

    我正在使用afnetworking使用basic auth调用web服务。问题是我得到了

    FAILURE: 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.}
    

    当我允许碎片,我得到

    Invalid value around character 0
    

    我和我们的Web开发人员谈过,他用“//”的方式对JSON响应进行前缀,因此我需要在我使用JSON之前修剪这些。我的问题是,我不确定如何访问响应来修剪和使用它,因为代码会立即转到故障块。

    let manager = AFHTTPSessionManager(baseURL: URL(string: "http://mydev1.kyfb.com/remote/appinfo.cfc?method=GetMemberInfo"))
                manager.requestSerializer.setAuthorizationHeaderFieldWithUsername(emailTextField.text!, password: passwordTextField.text!)
                // manager.responseSerializer = AFJSONResponseSerializer(readingOptions: .allowFragments)
                // manager.responseSerializer = AFHTTPResponseSerializer()
                manager.post("", parameters: nil, progress: nil, success: {
                    (task, responseObject) -> Void in
                    // TODO: If error message returned in JSON response, display error
                    // else login was successful. Save user info to User object and push AccountTableViewController
                    print("RESPONSE OBJECT: \(responseObject!)")
                    let responseJSON = responseObject as? [String: AnyObject]
                    print("RESPONSE JSON: \(responseJSON)")
                    if responseJSON!["MEMBERSHIPNUMBER"] != nil {
    
                    }
    
                }, failure: {
                    (operation, error) -> Void in
                    // TODO: Display error
                    print("FAILURE: \(error)")
                })
            }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Larme    6 年前

    如果你设置了 responseSerializer 作为 AFHTTPResponseSerializer 使用: manager.responseSerializer = AFHTTPResponseSerializer() ,然后 responseObject 应该是 (NS)Data 反对。

    做什么:
    获取的值 "//" (我们称之为 prefixData )中。
    检查是否 响应对象 有它的前缀。
    必要时拆下。

    let prefixData = "//".data(using: .utf8)!        
    //OR let prefixData = Data(bytes: [0x2F, 0x2F])
    
    let responsePrefix = responseObject.subdata(in: Range(0..<2))
    if responsePrefix == prefixData {
        let jsonData = responseObject.subdata(in: Range(2..<responseObject.count))
        //You got your JSON to serialize with Codable or JSONSerialization
    }
    

    使用强制展开和静默尝试(try?)的示例代码(不要那样做)为了逻辑:

    let prefixData = "//".data(using: .utf8)!
    print("prefixData from String: \(prefixData as NSData)")
    
    let prefixData2 = Data(bytes: [0x2F, 0x2F])
    print("prefixData from Bytes: \(prefixData2 as NSData)")
    
    if prefixData == prefixData2 {
        print("prefixData == prefixData2, use the one you want")
    }
    
    let responseObject = "//{\"key\":\"value\"}".data(using: .utf8)!
    print("responseObject: \(responseObject as NSData)")
    
    let responsePrefix = responseObject.subdata(in: Range(0..<2))
    if responsePrefix == prefixData {
        let jsonData = responseObject.subdata(in: Range(2..<responseObject.count))
        print("jsonData: \(jsonData as NSData)")
        let json = try? JSONSerialization.jsonObject(with: jsonData, options: [])
        print("json: \(json!)")
        let jsonString = String(data: jsonData, encoding: .utf8)
        print("jsonString: \(jsonString!)")
    } 
    

    输出:

    $>来自字符串的前缀数据:<2F2F>
    $>来自字节的前缀数据:<2F2F>
    $>prefixdata==前缀数据2,使用所需的
    $R.2F2F7B22 6B65 7922 3A227 661 6C75 65 22 7D & GT;
    $>jsondata:<7B226B65 79223A22 76616C75 65227D>
    $>json:可选({
    key=值;
    })
    $>jsonstring:{“key”:“value”}