0

Can anyone guide me how to print the web service request and response from dataTaskWithRequest in json format while using swift 4.0 and objective C.

Links tried:

How to print NSMutableURLRequest?

I can print them, but its not printing in proper format. I need in a format so that I can paste it in postman or web browser and test.

Request Format which I need:

eg:https://restcountries.eu/rest/v2/name/aruba?fullText=true

For Response:

Need the response format like the above url's response which I can view them in http://jsonviewer.stack.hu.

Prajnaranjan Das
  • 1,378
  • 1
  • 9
  • 26

4 Answers4

3

To get response objects in string and dictionary objects :

NSURLSessionDataTask *task = [session dataTaskWithRequest:URLRequest
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error) 
{ 
    // your code 

    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    id responseObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
}

To get pretty printed json format from NSData object or dictionary :

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

NSString *strData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"Params : %@", strData);

EDIT

To print json Request, try using this :

// for POST/JSON type

NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

// for GET type

NSLog(@"Request url : %@", [[request.URL absoluteString] stringByRemovingPercentEncoding]);
Ami Patel
  • 71
  • 6
  • @Prajnaranjan Das, check my edit here for printing request. – Ami Patel Feb 26 '18 at 06:37
  • Thanks @Ami Patel...But the above line only prints the parameters...I have edited my question... I need the request format in that way, so that I can paste in postman or web browser and test... – Prajnaranjan Das Feb 26 '18 at 06:43
  • @PrajnaranjanDas ok so you need to print a GET request. Will update for the same once I find a way. But at least you can mention about the response format that you needed if it was helpful to you. :) – Ami Patel Feb 26 '18 at 07:20
  • Thanks @Ami...Your function giving response like this e.g.::::::Response: "First_Approver_Code" = CP0001; "First_Name" = PDas; FlightDurationWindows = { Duration = 8; }; It should print the the json file, which I can copy and paste in jsonviewer and check… – Prajnaranjan Das Feb 26 '18 at 07:28
  • @PrajnaranjanDas Ok I found something for printing request. I am updating the answer, use it with your generated request url. – Ami Patel Feb 26 '18 at 07:35
  • Thanks for your reply.....[[request.URL absoluteString] stringByRemovingPercentEncoding]...It only prints the request URL..It don't print the parameters with that...I have updated my question...Please look once .. – Prajnaranjan Das Feb 26 '18 at 07:39
  • @PrajnaranjanDas Did you try what I updated for GET request? Try that first, it will give you the request in the format you are looking for. – Ami Patel Feb 26 '18 at 07:44
  • ....This get request only prints the request url ...It should combine the httpBody/parameters also.. – Prajnaranjan Das Feb 26 '18 at 07:49
  • @PrajnaranjanDas My answer also includes printing for request body. It deserves an upvote and accepted answer as it has helped you. – Ami Patel Feb 26 '18 at 07:52
  • Rally thanks for all your support..But I think u understood my question...So please try to answer that... I have given you a upvote... – Prajnaranjan Das Feb 26 '18 at 07:56
1

Swift 4

Use this function to print your request. Just pass your request to this function and remember that your request should be Dictionary.

   func prettyPrintRequest(with json: [String : Any]) -> String{
    let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    let string = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    if let string  = string{

        return string
    }
    print("something went wrong")
    return ""
}

UPDATED to objective c code

-(void)prettyPrintRequest:(NSDictionary*)request{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:request
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

if (jsonData) {
     NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"Valid Json String is %@", jsonString);

} else {
    NSLog(@"Error is : %@", error);

}
}
Vikky
  • 914
  • 1
  • 6
  • 16
1

For Printing the response in JSON format, so that you can copy/paste it into Postman and check.

In Objective C:

NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonString: %@", jsonString);

In Swift 4:

let dataString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
print(dataString)
Prajnaranjan Das
  • 1,378
  • 1
  • 9
  • 26
0

You can print JSON data like,

if error == nil {
    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
        print(json)
        let dic = json as! NSDictionary
        print(dic)
    }
    catch {
        print("Throw error when convert to json")
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Kamani Jasmin
  • 691
  • 8
  • 11
  • Thanks @Kamani Jasmin...But it don't print in proper json format...It print like this: Agent = { "Curr_Code" = INR; "OF_ID" = 141; "TA_Account_Freezed" = 0; "TA_CL_Amount" = "110010990464157.00"; "TA_ID" = 3373; "User_ID" = 123555; }; – Prajnaranjan Das Feb 26 '18 at 05:38
  • @PrajnaranjanDas Yes because its a dictionary. But why do you exactly need to print json while key value pair is same in dictionary too? – TheTiger Feb 26 '18 at 07:43
  • @TheTiger... I want to check them in json viewer...which is easier to read...In which I can expand and collapse any array and dictionary with a big json.. – Prajnaranjan Das Feb 26 '18 at 07:52
  • @PrajnaranjanDas Json viewer also provides the JSON from URL why you need to do it programmatically? You can use `Postman` extension of chrome or `http://hurl.it/` to see the response. – TheTiger Feb 26 '18 at 07:57
  • @TheTiger... Yes I know that...but I have asked the same question here...How to print that full request URL ???... – Prajnaranjan Das Feb 26 '18 at 07:59
  • @PrajnaranjanDas You are making the request with params yourself? You have a URL and parameters you can use them in browser.... I'm not getting why you need to print? – TheTiger Feb 26 '18 at 08:05
  • @TheTiger... https://restcountries.eu/rest/v2/name/aruba?fullText=true... This url is just an example.... I need to print my request url same like this... – Prajnaranjan Das Feb 26 '18 at 08:06
  • @PrajnaranjanDas Go to [jsonlint](https://jsonlint.com/) and just paste above url and click on ValidateJson button. – TheTiger Feb 26 '18 at 08:09
  • Although this is not recommended but here is how you can print... `do { print (try String(contentsOf: URL(string: "https://restcountries.eu/rest/v2/name/aruba?fullText=true")!, encoding: String.Encoding.utf8)) } catch {}` – TheTiger Feb 26 '18 at 08:33