在ObjC工作,而不是迅速。我在swift中使用JSON解析是错误的

时间:2017-08-30 14:40:18

标签: ios objective-c swift nsjsonserialization

我只想从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)
        }

    }

2 个答案:

答案 0 :(得分:0)

您的代码正在发送一个有效的请求正文:

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

这是不正确的。

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

  • 如果您的服务器需要application/x-www-form-urlencoded请求,则该值不能包含空格,换行符或其他任何保留字符。在这种情况下,您必须“百分比逃脱”请求的正文。

您应该确切地确认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)
    }
}

答案 1 :(得分:0)

在你的swift代码中,你附加了以下字符串。

double stepTime(const vertex_descriptor& source, const vertex_descriptor& target, const std::vector<uint8_t>& elevation) / 在下一行中,您将附加带有可选值的JsonString,并带有此“()”的可选关键字。因此,您需要打开可选值 /

let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8)