Escaped double-quotes appear in string during debugging - ios

I have a dictionary and I need to generate a JSON string by using NSMutableArray. Here is my code:
NSDictionary *dict = #{
#"From":From,
#"To":To,
#"DepartureDate":DepartureDate,
};
[FinalArray addObject:dict];
Then I generate the JSON String like this:
NSError *error;
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:FinalArray
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData=%#", jsonString);
Now output is on NSLog like this:
[
{
"From": "city",
"To": "city",
"DepartureDate": "20160301"
}
]
But while I'm debugging, at a breakpoint, the string appears with escaped double-quotes:
"[{\"From\":\"city\",\"To\":\"city\",\"DepartureDate\":\"20160301\"}]"
Why is that?

That's a stringified json object. My guess is that to allow the json to be shown in the console it's stringified, adding the escaped quotes. In your runtime the backslashes don't exist, they are only there to correctly display the json in the console.

Related

JSON creation in objective c, invalid JSON

I am creating a JSON to be sent in service on checking online its showing error:
Error: Parse error on line 1:
[{\ "SAHExpertCode\"
--^ Expecting 'STRING', '}', got 'undefined'
My JSON is [{\"SAHExpertCode\" : \"\", \"ShiftType\" : \"AM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]
Please tell me what's wrong and how to correct it.First i am making JSON filterString = [{ "SAHExpertCode" : "", "ShiftType" : "AM", "LocFunId" : "CLT0004218","SAHQualCode" : "CA" }] on checking found it is correct then creating a dictionary NSDictionary*dictData=#{#"MbrId":[USER_DEFAULTS valueForKey:#"MemberId"],#"StrFilter":[NSString stringWithFormat:#"%#",filterString],#"shiftCrtlNos":shftCntrlNmbrs}; NSMutableArray *finalArray = [[NSMutableArray alloc]init]; [finalArray addObject:dictData]; NSString *finalString =[self ConvertArrayToJsonData:finalArray];finalString = [finalString stringByReplacingOccurrencesOfString:#"\n" withString:#""]; finalString = [finalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];after creation of final string it is generating symbol \ for JSON Conversion my code is -(NSString *)ConvertArrayToJsonData:(NSMutableArray *)array{ NSError error;
NSData jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; NSString *JSONString; if (!jsonData) { NSLog(#"error :%#",error); } else {JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; // NSLog(#"jsonstring:%#",JSONString);
}
return JSONString;
}
//i need JSON like [ { "StrFilter" : "[ { \"SAHExpertCode\" : \"\", \"ShiftType\" : \"PM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]", "MbrId" : "MBR0000035", "shiftCrtlNos" : "0080013526,0080014697" }] also tell me how to remove \ from String
i replaced the unwanted \ symbols by doing
finalString = [finalString stringByReplacingOccurrencesOfString:#"\" withString:#""]; in the JSON string.
I suggest you go to www.json.org and look at the correct formatting of JSON data. And the easiest way to get correctly formatted JSON is to create an array or dictionary that you want to convert to JSON, and use NSJSONSerialization to do the job.
Just use default NSJSONSerialization method of iOS
in below example i have a "postMenuArray" which I'm converting in JSON.
NSData * postMenuSerial = [NSJSONSerialization dataWithJSONObject:postMenuArray options:0 error:nil];
NSString *Menujson = [[NSString alloc] initWithBytes:[postMenuSerial bytes] length:[postMenuSerial length] encoding:NSUTF8StringEncoding];
Here I got JSON response
Menujson = [Menujson stringByReplacingOccurrencesOfString:#" "withString:#""];
Lastly I remove all the spacing .
Still facing issue try this
Menujson = [Menujson stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Creating a json object dynamically

I have to make json request of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
Following is the way how im creating the json.
NSString *json = [NSString stringWithFormat:#"{\"documents\": [ { \"file_size\": %#, \"file_name\": %#\", \"file_content\": \"%#\" } ]}",_imageSizeArray[0],_imageNameArray[0],_baseArray[0]];
but the problem is that, the documents array may even contain more than one json object within it. If thats the case How can i create a jsonobject dynamically and embed it within documents array?
You have to take Array and add document object in that array
than at request time you have to convert your array to json string by following code
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Converting NSString to proper JSON format

Converting NSString to proper JSON format..
NSString *input_json = [NSString stringWithFormat:#"{\"id\":\"%#\",\"seconds\":\"%d\",\"buttons\": \"%#\"}", reco_id, interactionTime, json_Buttons];
Here json_Button is in json format converted from nsdictionary..
My input_json result is:
{"id":"119","seconds":"10","buttons": "{
"update" : "2",
"scan" : "4"
}"}
It is not in a proper JSON format. key buttons contain "{}" I want to remove these quotes.
Expected Result is:
{
"id": "119",
"seconds": "10",
"buttons": {
"update": "2",
"scan": "4"
}
}
You are going about this all wrong. First, create an NSDictionary that contains all of the data you want converted to JSON. Then use NSJSONSerialization to properly convert the dictionary to JSON.
Something like this will work:
NSDictionary *dictionary = #{ #"id" : reco_id, #"seconds" : #(interactionTime), #"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
} else {
NSLog(#"Unable to convert dictionary to JSON: %#", error);
}
It's a bad idea to try to build JSON strings manually. Use the NSJSONSerialization class. That makes it easy. Create your dictionary, then call dataWithJSONObject:options:error:.
If you use options: NSJSONWritingPrettyPrinted it inserts line breaks and whitespace that makes the JSON more readable.
By using that function you get correctly formatted JSON every time, and it's flexible because if you send it a different dictionary you get different JSON.

How to set NSString value to NSMutable dictionary?

I am implementing web-service APIs, data content type is of JSON. The body of the request should be in a string format i.e in double quotes but when I set it in a dictionary, I get the below result. Could anyone help me to set the NSString as string value in dictionary.
NSMutableDictionary *reqParams = [NSMutableDictionary new];
[reqParams setObject:#"Data.SourceStreamRequest"forKey:#"_type"];
NSMutableDictionary *reqParams1 = [NSMutableDictionary new];
[reqParams1 setObject:#"newmjpegdataSession"forKey:#"_type"];
NSLog(#"%#:%#",reqParams,reqParams1);
Output
{
"_type" = "Data.SourceStreamRequest";
}:{
"_type" = newmjpegdataSession;
}
Could anyone help me to figure out the reason why ,the dictionary values are shown with double quotes and without double quotes.
Thank you
Use NSJSONSerialization to serialize your dictionary. Try this:
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"_type", #"Data.SourceStreamRequest",
#"_type", #"newmjpegdataSession", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"json:\n%#", resultAsString);
Output:
json: { "newmjpegdataSession" : "_type", "Data.SourceStreamRequest"
: "_type" }

NSData to NSString with JSON response

NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.

Resources