How to show JSON response in iPhone using the objective c by dynamically adding " \" to the keys?

37 Views Asked by At

I am having a sample code which helps me to print the JSON response. In this I manually added the \ slash symbol before keys and values so it helps me to print the JSON . The code is :

NSString *jsonString = @"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";

Now the problem is once the JSON string gets longer I have to manually add the \ before every key.

Can someone help of how I can add "" before the keys as shown in the code above using some looping code?

Any help will be appreciated.

1

There are 1 best solutions below

0
DonMag On

It's really not clear what you're trying to do - but maybe this will work...

Use:

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement;

The target will be ", and you'll need to escape it like this:

@"\""

The replacement will be \", escaped like this:

@"\\\""

So, this:

NSString *jsonString = @"[{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
NSLog(@"%@", [jsonString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]);

will output this to the debug console:

2022-10-11 12:35:58.958881-0400 YourProj[6562:7795515] [{\"person\": {\"name\":\"James\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]

When receiving json from remote, it might look like this:

NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSString *js = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", [js stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]);