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

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.

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:#"\\\""]);

Related

How do I urlencode this NSString that contains a JSON inside it?

I have the following json string that should be sent to the backend
{
id = "MU_200255802";
keywords = (
Talk,
games,
meetup,
time,
meet,
"Time for Another Game"
);
}
So before this JSON I have the java servlet URL something like
http://....net/servletName?
How should I urlencode the json string and the url because even after trying several options, I keep getting bad url as an error back in the delegate method. What is the right way to do it/
I tried encoding using
NSString *urlStringEncoded = [[NSString stringWithString:urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and also used other encoding formats too.
Use this to create json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:#"Your object" options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
You can use Google Toolbox for Mac, check it out here, https://code.google.com/p/google-toolbox-for-mac/source/checkout
There are Classes named GTMNSString+HTML,GTMNSString+XML,GTMNSString+URLArguments, which contains many encoding methods for you.

Encode JSON data for URL

In iOS, I want to send JSON data in URL to make service call. I tried following code snipped but Encoded URL seems wrong. Because in JSON there is a colon character (:) between key and value and comma character (,) for separation. But, i am not able to encode colon(:) as %3A and comma(,) as %2C
Code Snippet:
- (NSURL *)getEncodedUrl {
// Build dictionnary with parameters
NSString *abc = #"abc";
NSNumber *limitNumber = [NSNumber numberWithInt:2];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:limitNumber forKey:#"limit"];
[dictionnary setObject:abc forKey:#"abc"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
if (!jsonData) {
debug("Json error %#",error);
return nil;
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
debug("Json op %#",JSONString);
NSString* params = [JSONString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://baseUrl.com?param=#",params]];
debug("URL = %#",url);
return url;
}
}
OUTPUT:~
URL = http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D
(Include colon and comma characters)
But I want following o/p:
http://baseUrl.com?param=%7B%22abc%22%3A%22abc%22%2C%22limit%22%3A2%7D
(No colon and comma characters)
Online Encoding-Decoding Site that I am referring as of now.
http://www.url-encode-decode.com/
you can simply use
NSString *url = #"http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D";
NSString *encodeImgUrl = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'd recommend that you send the JSON as POST data instead of the GET that you're using. It'd be more straightforward to package it as MIME data and any encoding you do would be easier to understand.
So you are trying to generate the query portion of a URL here. Colons are a perfectly legitimate character to include in URL queries. I wrote an article covering the intricacies of escaping URL queries in Cocoa:
http://www.mikeabdullah.net/escaping-url-queries-in-cocoa.html
Since you're keen to perform extra escaping, I suggest taking my sample code and extending it to specially ask for : and ; characters to be escaped too.
I made small mistake in API call that is why I am getting wrong result. There is no need to encode colon(:) as %3A and comma(,) as %2C.
One more thing I would like to share with you. You can use base64 string instead of encoding JSON part.

Add double quote to NSString attach to the variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to initialize NSString as text with double quotes
How can I add tan actual double quote to a variable inside on NSString to be used in NSDictionary?
Example
NSString *ename=#"John Doe";
NSDictionary *profile=#{#"Profile":#{"Name":ename}};
I need to display like this "Profile":{"Name":"John Doe"}
I need to display like this "Profile":{"Name":"John Doe"}
Do you want to create JSON format? Then you can use the built-in class NSJSONSerialization:
NSString *ename = #"John Doe";
NSDictionary *profile = #{#"Profile":#{#"Name":ename}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:profile options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"Profile":{"Name":"John Doe"}}
Use escape charater \ ...
NSString *ename=#"This is double \" quote \"";
If you are asking for adding quotes in Key of dictionary, then you have to add some special character, (non-alphabet and non-numerical) only then key shows double quotes.
[... description] simply wraps things in quotes for display that have non-alphanumeric characters in them.
And there is no difference between "abc" and abc in debugger. This is used only for dubugging and the actual value is always a NSString #"abc".
Check this
NSString *string=#"This is test \" for \"";
Hope it helps you..

responseString is null

my webservice returns json string with new lines so It causes problem that responseString gives always null.
NSString *responseString=[[NSString alloc] initWithData:kampanyadata encoding:NSUTF8StringEncoding];
NSLog(#"%#",[NSString stringWithFormat:#"responsestring:%#",responseString]);
----responsestring:null
how can I replaces new lines character in JSON String?
NSString *tempString = [tempString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
I think you need to do this :)
Are you sure kampanyadata is not null? If it's not null try to use NSASCIIStringEncoding like this:
NSString *responseString=[[NSString alloc] initWithData:kampanyadata encoding:NSASCIIStringEncoding];.
Offtopic
And btw the NSLog(); method takes a NSString formatted already as parameter so you can use:
NSLog(#"responsestring:%#",responseString);
soapResults = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
try this this works fine for me
You got some NSData, and you tried to convert it to an NSString. There's no JSON involved at this point. Any errors have nothing to do with JSON or newline characters whatsoever. Possibilities: 1. The NSData that you received is nil. 2. The NSData that you received isn't in UTF-8 format.
Your NSLog statement is quite funny. Look at the definition of NSLog - the first parameter is a format string. Instead of
NSLog(#"%#",[NSString stringWithFormat:#"responsestring:%#",responseString]);
you should write
NSLog (#"responseString:%#", responseString);
And you can pass the JSON document directly to NSJSONSerializer. No need to convert it to an NSString. Actually, if the data is large, just a waste of valuable memory.

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'أنك واهم'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya أيدت الثورة السورية منذ بدايتها وارجع لليوتوب واكتب( سوريا السويدان )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "أنك واهم", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources