在 ObjC 中工作,而不是在 swift 中工作。我在 JSON 中解析 swift 有什么问题

Working in ObjC, not in swift. Whats wrong I am doing with JSON parsing in swift

我只想从 URL 解析 JSON, 下面用 ObjC 编写的代码运行良好并且给了我正确的响应, 但是在swift 3.1 中写的代码,没有给出正确的响应。 给我 500 Internal Error

我做错了什么。 谁能指导一下。 提前致谢。

我还尝试使用从 ObjC 到 Swift 的转换器。 但是它失败并出现一些错误,虽然我解决了这些错误,但仍然没有给出正确的输出。

下面的 ObjC 代码。

-(void)comparedatainserturl

{
    NSError *error;
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];

    [dict setObject:@"e639e129d0f3ab7d" forKey:@"imei_no"];
    [dict setObject:@"2017-08-29 12:18:44" forKey:@"current_time"];
    [dict setObject:@"0" forKey:@"tbl_offer_details"];
    [dict setObject:@"0" forKey:@"tbl_card_type"];
    [dict setObject:@"0" forKey:@"tbl_dashboard"];
    [dict setObject:@"0" forKey:@"tbl_category_details"];
    [dict setObject:@"0" forKey:@"tbl_sub_category_details"];
    [dict setObject:@"0" forKey:@"tbl_payment_option"];
    [dict setObject:@"0" forKey:@"tbl_payment_option_provider"];
    [dict setObject:@"0" forKey:@"tbl_like_favorite_share"];
    [dict setObject:@"0" forKey:@"tbl_user_details"];

    [arr addObject:dict];

    NSLog(@"arra :- %@",[arr description]);

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSString *string = [NSString stringWithFormat:@"data=%@",jsonString];

    NSLog(@"jsonData as string:\n%@", string);

    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

    NSString *urlString=[NSString stringWithFormat:@"%@",@"http://admin.scontos.com/index.php/Android_api/Offers_download"];

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod: @"POST"];

    [request setHTTPBody: data];

    NSError *err;

    NSURLResponse *response;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

    NSLog(@"gotresponsestring=%@", resSrt);
}

Swift 代码如下,

func  comparedatainserturl() {


        var arrayParams : NSDictionary = [:]

        arrayParams  = ["imei_no":"e639e129d0f3ab7d","current_time":"2017-08-2911:08:26","tbl_offer_details":"0","tbl_card_type":"0","tbl_dashboard":"0","tbl_category_details":"0","tbl_sub_category_details":"0","tbl_payment_option":"0","tbl_payment_option_provider":"0","tbl_like_favorite_share":"0","tbl_user_details":"0"]

        print(arrayParams)

        let valueArr : Array = [arrayParams]
        print(valueArr)

        let jsonData: Data? = try! JSONSerialization.data(withJSONObject: valueArr, options: .prettyPrinted)

        let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8)
        let string: String = "data=\(jsonString)"
        print("jsonData as string:\n\(string)")
        let dataa: Data? = string.data(using: String.Encoding.utf8)

        var _: NSError?
        let url1:URL = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
        let request:NSMutableURLRequest = NSMutableURLRequest(url: url1)
        request.httpMethod = "POST"

        request.httpBody = dataa

        var response: URLResponse?

        do{
            let urlData: Data? = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)


            let resstr = NSString(data: urlData!, encoding: String.Encoding.utf8.rawValue)
            print("Response is \(resstr! as String)")

        }catch{
            print(error)
        }

    }

您的代码发送的请求正文实际上如下所示:

data=[
  {
    "key1" : "value1", 
    "key2" : "value2", ...
  }
]

这是不正确的。

  • 如果您的服务器只需要 JSON,您应该发送不带 data= 前缀的 JSON。

  • 如果您的服务器期待 application/x-www-form-urlencoded 请求,则该值不能包含空格、换行符或任何其他保留字符。在这种情况下,您必须 "percent escape" 请求的正文。

您应该准确确认 Web 服务的期望,并相应地调整您的代码。


不相关,我会退休 NS 类 并留在 Swift 内。因此,假设您只想发送 JSON,代码可能如下所示:

func comparedatainserturl() {
    let arrayParams = [
        [
            "imei_no":"e639e129d0f3ab7d",
            "current_time":"2017-08-2911:08:26",
            "tbl_offer_details":"0",
            "tbl_card_type":"0",
            "tbl_dashboard":"0",
            "tbl_category_details":"0",
            "tbl_sub_category_details":"0",
            "tbl_payment_option":"0",
            "tbl_payment_option_provider":"0",
            "tbl_like_favorite_share":"0",
            "tbl_user_details":"0"
        ]
    ]

    let data = try! JSONSerialization.data(withJSONObject: arrayParams)

    let jsonString = String(data: data, encoding: .utf8)!
    let string: String = "data=" + jsonString
    print("jsonData as string:\n\(string)")

    let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
    var request = URLRequest(url: url1)
    request.httpMethod = "POST"        
    request.httpBody = data

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print(error)
            return
        }

        guard let data = data else { return }

        let string = String(data: data, encoding: .utf8)
        print("response is \(string)")
    }
    task.resume()
}

或者,如果服务器期望 x-www-form-urlencoded 请求:

let data = try! JSONSerialization.data(withJSONObject: arrayParams)

let jsonString = String(data: data, encoding: .utf8)!
let string: String = "data=" + jsonString.addingPercentEncodingForQuery()!

let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
var request = URLRequest(url: url1)
request.httpMethod = "POST"
request.httpBody = string.data(using: .utf8)

你使用这个例程逃脱的地方,改编自 Alamofire 的 escape routine:

extension String {
    public func addingPercentEncodingForQuery() -> String? {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return addingPercentEncoding(withAllowedCharacters: allowed)
    }
}

在您的 swift 代码中附加以下字符串。

let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8) /在下一行中,您将使用带有此“()”的可选关键字附加带有可选值的 JsonString。所以你需要打开可选值/

let string: String = "data=\(jsonString!)"