How to print the web service request and response from dataTaskWithRequest - ios

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.

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]);

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);
}
}

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")
}
}

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)

Related

Convert NSString in to NSDictionary

I'm using JSON POST approach, my code is
[_urlReq setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[_urlReq setHTTPMethod:#"POST"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long) [postData length]];
[_urlReq setValue:postLength forHTTPHeaderField:#"Content-Length"];
[_urlReq setHTTPBody:postData];
_dataTask = [_urlSession dataTaskWithRequest:_urlReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!(data == nil)) {
I'm converting response data in to string formate
NSString* myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];// NSUTF8StringEncoding
NSLog(#"myString :%#", myString);
OutPut:
myString :{"Response":{"status":"SUCCESS","error_code":"0","message":"message","Array":[{"name" => "VVV","name" => "CHE","ac" => "5a8805a","email" =>"vvv","line1" =>"","line2" =>"","no" =>"","street" =>"","pin_code" =>"","state_id" =>"0","district_name" =>"0"}]}}
//Convert string into Dic
NSData *data1 = [myString dataUsingEncoding: NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];
NSLog(#"json : %#", json);
NSLog(#"Response : %#",[json objectForKey:#"Response"]);
//Second approach to convert string to dic
NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSLog(#"array :%#", array);
NSDictionary *dictionary = [array objectAtIndex:0];
NSLog(#"dictionary : %#", dictionary);
NSString *test = [dictionary objectForKey:#"Response"];
NSLog(#"Test is %#",test);
}
I don't know what is the problem here....
You JSON format is Starting with Dictionary.
Instead of,
NSArray *array = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSLog(#"array :%#", array);
Replace this and Try
NSDictionary *jSonDict = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
Second Try:
NSDictionary *jSonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
For more info, how to validate JSON, use this link enter link description here
Your JSON:
Replace JSON response string with this
{"Response":{"status":"SUCCESS","error_code":"0","message":"message","Array":[{"name" : "VVV","name" : "CHE","ac" : "5a8805a","email" : "vvv","line1" : "","line2" : "","no" : "","street" : "","pin_code" : "","state_id" : "0","district_name" : "0"}]}}
Your json string is not correct. Please check my demo json string.
try this
let myString :String = "{\"Response\":{\"status\":\"SUCCESS\",\"error_code\":\"0\",\"message\":\"message\",\"Array\":[{\"name\" : \"VVV\",\"name\" : \"CHE\",\"ac\" : \"5a8805a\",\"email\" :\"vvv\",\"line1\" :\"\",\"line2\" :\"\",\"no\" :\"\",\"street\" :\"\",\"pin_code\" :\"\",\"state_id\" :\"0\",\"district_name\" :\"0\"}]}}"
if let data = myString.data(using: .utf8){
do{
let json = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0));
print(json)
}catch{
}
}
Output
{
Response = {
Array = (
{
ac = 5a8805a;
"district_name" = 0;
email = vvv;
line1 = "";
line2 = "";
name = VVV;
no = "";
"pin_code" = "";
"state_id" = 0;
street = "";
}
);
"error_code" = 0;
message = message;
status = SUCCESS;
};
}

Converting NSData to NSDictionary

I am trying to fetch data from an url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json
I am getting nil while converting nsdata to nsdictionary.
I used the following code. and I am able to log the data as well. but as soon as I convert it into dictionary it is showing nil.What am I missing here?
I tried nsurlsession and afnetworking as well. getting the same error.
NSError *error;
NSString *url_string = [NSString stringWithFormat: DATA_URL];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"json: %#", json);
You have to convert NSDatainto UTF8 before parsing it using NSJSONSerialization.
NSError* error = nil;
NSString *strISOLatin = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSData *dataUTF8 = [strISOLatin dataUsingEncoding:NSUTF8StringEncoding];
id dict = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:0 error:&error];
if (dict != nil) {
NSLog(#"Dict: %#", dict);
} else {
NSLog(#"Error: %#", error);
}
If you are looking for the Swift equivalent of Jayesh Thanki's Objective-C code, here it is,
let str = String(data: d, encoding: .isoLatin1)
let data8 = str?.data(using: .utf8)
let result = try JSONSerialization.jsonObject(with: data8!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

Deserialise JSON String in Objective C

I received NSData object data from REST API. That contains JSON data which I want to parse.
{
JsonResult = "[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
}
This statement gave me the result as a String like below which I am not able to parse as JSON.
myData = [data valueForKey:#"JsonResult"];
"[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
When I try to pass this mydata to JSONSerialization the code crashes.
How do I cast the above string to NSDictionary so that I can parse them and use the values of IsAuth and User.?
Code:
[LDService authenticateUser:Uname.text passwordString:Password.text completeBlock:^(NSData * data){
NSError *error;
NSData *jsonData;
NSString *jsonString = nil;
NSMutableDictionary *jsonDict;
if([NSJSONSerialization isValidJSONObject:data])
{
jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
NSLog(#"Formatted string %#",formattedString);
[jsonDict setObject:formattedString forKey:#"JsonResult"];
NSLog(#"Parsed json %#",jsonDict);
}];
Pass your data as data
NSError *error;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:data])
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
then replace occurance of #"\\\" with #"'"
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
then use this formattedString.
I have investigates your json file from Json formatter & Validator, there are lots of error in your json file, so first check your file from this validator and this formatter gives you error with description. Re-build your json file, if you still getting any problem then ask.

Best way to display JSON (well formatted) in UITextView or UIWebView in iOS

I need to display JSON in my iPhone app. Currently I am getting unformatted JSON - like one big string with no indentation.
What would be the best way to display this?
Thanks,
to get formatted JSON string.
The solution is to create JSON Object from JSON string,
and then convert the JSON object back to JSON String, using .PrettyPrinted option.
The code is
let jsonString = "[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]"
var error: NSError?
//1. convert string to NSData
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
//2. convert JSON data to JSON object
let jsonObject:AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)!
//3. convert back to JSON data by setting .PrettyPrinted option
let prettyJsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted, error: &error)!
//4. convert NSData back to NSString (use NSString init for convenience), later you can convert to String.
let prettyPrintedJson = NSString(data: prettyJsonData, encoding: NSUTF8StringEncoding)!
//print the result
println("\(prettyPrintedJson)")
The result will look like this
Objective-C code
NSString *jsonString = #"[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];
NSData *prettyJsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
NSString *prettyPrintedJson = [NSString stringWithUTF8String:[prettyJsonData bytes]];
NSLog(#"%#", prettyPrintedJson);
here's the Objective-C code.
NSString+PrettyPrint.h
#interface NSString (PrettyPrint)
+ (NSString * _Nonnull)prettifiedJsonStringFromData:(nullable NSData *)data;
+ (NSString * _Nonnull)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary;
#end
NSString+PrettyPrint.m
#import "NSString+PrettyPrint.h"
#implementation NSString (PrettyPrint)
+ (NSString *)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary {
if (dictionary == nil) { return #"nil"; }
NSMutableString *returnStr = [NSMutableString stringWithString:#"[ \n"];
for (NSString *key in dictionary) {
[returnStr appendFormat:#" %#: %#,\n", key, [dictionary valueForKey:key]];
}
[returnStr appendFormat:#"]"];
return returnStr;
}
+ (NSString *)prettifiedJsonStringFromData:(nullable NSData *)data {
if (data == nil) { return #"nil"; }
NSData *jsonData;
NSError *error = nil;
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject == nil) {
return #"nil (json object from data)";
} else {
BOOL isValidJsonObject = [NSJSONSerialization isValidJSONObject:jsonObject];
if (isValidJsonObject) {
NSData *finalData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
//TODO: error description
NSString *prettyJson = [[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding];
return prettyJson;
} else {
return [NSString stringWithFormat:#"%#\n%#", jsonStr, #" (⚠️ Invalid json object ⚠️)\n"];
}
}
}
#end
then call methods when u need to use them.
ex1. Print NSData for body, response ...etc
NSLog(#"body: %#", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);
ex2. Print NSDictionary
NSLog(#"headers: %#", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);
Probably you'll get these results in log.
Bear in mind, if you are dealing with Encodable objects you can use JSONEncoder for pretty printing.
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let jsonData = try? encoder.encode(obj) else {
return
}
let text = String(decoding: jsonData, as: UTF8.self)

NSJSONSerialization and Emoji

I'm currently trying to POST some JSON containing emojis to a python API. I tried feeding the NSJSONSerialization directly with the string containing the emojis from my UITextField but the serializer crashed with no meaningful explanation.
Afterwards I tried to do some format conversion and ended up with something like this:
NSString *uniText = mytextField.text;
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding] ;
This basically works except that the resulting UTF-8 is kinda double-"escaped" resulting in the following:
"title":"\\ud83d\\udc8f\\ud83d\\udc8f\\ud83d\\udc8f\\ud83d"
Any suggestions how to fix that?
There are two difficulties:
1. Apple hosed NSString WRT UTF Planes 1 and above, the underlying use
of UTF-16 shows through. An example is that length will return 2 for
one emoji character.
2. Whoever decided to put emoji in Plane 1 was
just being difficult, it is the first use of Plane 1 and a lot of
legacy UTF code does not handle that correctly.
Example code (adapted from #Hot Licks):
Updated with OP emoji
NSString *uniText = #"💦💏👒👒💦";
NSDictionary* jsonDict = #{#"title":uniText};
NSData * utf32Data = [uniText dataUsingEncoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"utf32Data: %#", utf32Data);
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
if (jsonData == nil) {
NSLog(#"JSON serialization error: %#", error);
}
else {
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"The JSON result is %#", jsonString);
NSLog(#"jsonData: %#", jsonData);
}
NSLog output
utf32Data: a6f40100 8ff40100 52f40100 52f40100 a6f40100
The JSON result is {"title":"💦💏👒👒💦"}
jsonData: 7b227469 746c6522 3a22f09f 92a6f09f 928ff09f 9192f09f 9192f09f 92a6227d
Sigh:
NSString* uniText = mytextField.text;
NSDictionary* jsonDict = #{#"title":uniText};
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJsonObject:jsonDict options:0 error:&error];
if (jsonData == nil) {
NSLog(#"JSON serialization error: %#", error);
}
else {
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"The JSON result is %#", jsonString);
}
If myTextField.text is a valid NSString then no other conversions should be required. NSJSONSerialization will provide all necessary "escaping".

Resources