How to create JSON format string in iphone? - iphone

I want to create JSON string like {"search_element": "New York"} this. I used following code for that.
NSString *JSONString = [NSString stringWithFormat:#"{\"search_element\":""\"%#\"""}",
[searchName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
After doing this I am getting value like {"search_element":"New%20York"} this. I want it should be New York instead New%20York. I am not getting How to format it for expected result.Please help me.

Can't you just use it like that?
NSString *JSONString = [NSString stringWithFormat:#"{\"search_element\":""\"%#\"""}", searchName];
So basically without the stringByAddingPercentEscapesUsingEncoding: method
And I don't really understand why do you use that:
#"{\"search_element\":""\"%#\"""}"
I'd do it with less quotation marks:
#"{\"search_element\":\"%#\"}"
Did a quick test:
NSString *test = #"{\"search_element\":\"%#\"}";
NSLog(test, #"New York");
output:
{"search_element":"New York"}
Hope it helps

you can simply call next
NSString *newString = [JSONString stringByReplacingOccurrencesOfString:#"%20" withString:#""];
However look into JSONKit and SBJSON ..they have methods to make valid JSON in iOS

Related

How to generate a JSON string compatible with Objective-C syntax

I need some kind of json string generator for objective-c. Actually I thought there must be something like that but I could not find anything.To be specific, for example I have a json string like:
{"name":"abc","email":"def#ghi.com","password":"1"}
when I want to store it in objective c, I have to write it like:
#"{\"name\":""\"abc\""",\"email\":""\"def#ghi.com\""",\"password\":""\"1\"""}"
so it is confusing and hard to implement. Are there any generators or an easy way to implement it. Thanks
Convert your json string to dictionary...
NSData* data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"jsonDict:%#",jsonDict);
You can use the native ios SDK API's for generating JSON data from NSDictionary / NSArray.
e.g.,
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:(dictobject) options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
may this helps!
Use it
Also Import"JSON.H"
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL:[NSURL URLWithString:website] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
be careful...in your original question, when referring to how to store it in objective-c, i think you made a mistake
you wrote :
#"{\"name\":""\"abc\"""
when it shoud be
#"{\"name\":\"abc\",....etc...
i think you doubled the quotes...be wary, cause in the beginning there already is one opening double-quote #", all the other needed quotes must be escaped like so \", and then also have an ending quote as well.
hope it helps

how to add variable into an url

I am getting userid through parsing a link.Again i have to parse it with userid to get the access.
What i am doing
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/fb_redirect_mobile/?accessToken=4546"];
This gives me the userid,now i want to use that userid to parse it again such as:
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/userid/bookmarks"];
In other languages I have seen they are just using:
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
The userid variable takes user id.how i can do this in iPhone.I know my question is lengthy but i tried to make it clear what i want.please help..please also tell me how to store a parsing id into string,such as userid i am going to get after parsing the url./now how i can save it in form of string.
NSString *userId = #"123456";
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/%#/bookmarks", userId];
initWithFormat:/stringWithFormat: follow the general format convention set by printf/scanf
The way you concatenated your userid is not valid syntax in Obj-C
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
What you'd probably want to do is use a format specifier for an Obj-C object (in your case NSString), and use that within your URL (assuming userid is an NSString, which it probably is. If it's a C based string, use %s as your format specifier instead).
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/%#/bookmarks", userid];
Refer to these on how to use stringWithFormat: on an NSString:
Formatting String Objects
String Format Specifiers
you can give like this,
NSString *str=[NSString stringWithFormat:#"http://abc.com/user/%#/bookmarks",userid];
Instead of
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
You would use
NSString *str=[[NSString alloc] initWithFormat:#"http://abc.com/user/%#/bookmarks",userid];
Well you almost got it:
NSString *usrid = #"4546";
NSString *str=[NSString stringWithFormat:#"http://abc.com/fb_redirect_mobile/?accessToken=%#", userid];
You can use the stringWithFormat: method of NSString for this.

Instance method '-jsonValue'not found (return type defaults to 'id')

I got problem in following statement.
NSArray *feedsData = [strFeedsResponse JSONValue];
I presume strFeedsResponse is an instance of NSString. There is no such method as JSONValue in NSString. You need NSString category and add the JSONValue method there.
You can use for example SBJson library https://github.com/stig/json-framework/, which contains NSString+SBJson.h header, which adds the JSONValue method for NSString.
This header must be than imported in the source file where you want to use the JSONValue method:
#import NSString+SBJSON.h
More about categories for example here: http://macdevelopertips.com/objective-c/objective-c-categories.html
One of two things is happening:
strFeedsResponse is not ACTUALLY an instance of an NSString. Maybe it is null or it has been initiated with an incorrect value. You can add a breakpoint to your code to check the value that is stored in strFeedsResponse before you call JSONValue on it.
You have not correctly imported the JSON framework that you are using into your class. You need to add the JSON header to your class.
Hope this helps future searchers on this error...
The reason for the error is that the current version of SBJson seems to not contain the NSString category "NSString+SBJSON.h" referred to by an earlier poster. So, you could easily write your own, or just use the SBJsonParser class directly ("address" is just an NSString containing something like "24 Elm Street, Yourtown, New Mexico"):
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *response = [NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *googleResponse = [parser objectWithString:response];
Cheers!
If you are using a webservice, then give the URL for that.
try this way...
NSArray* latestentry = (NSDictionary*)[responseString JSONValue];
NSArray *feedsData = [[strFeedsResponse JSONValue] mutableCopy];
Use this Line, it will be useful to you..
This error generally comes when method not found.Here it comes because JSONValue function is not found.
Please make sure you have included json header files where you calling this function.

How to combine two strings in Objective-C for an iPhone app

How can I combine "stringURL" and "stringSearch" together?
- (IBAction)search:(id)sender;{
stringURL = #"http://www.websitehere.com/index.php?s=";
stringSearch = search.text;
/* Something such as:
stringURL_ = stringURL + stringSearch */
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringURL_]]];
}
Philippe gave a good example.
You can also use plain stringWithFormat: method.
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This way you can manipulate string even more by putting somethig inbetween the strings like:
NSString *combined = [NSString stringWithFormat:#"%#/someMethod.php?%#", stringURL, stringSearch];
NSString* combinedString = [stringUrl stringByAppendingString: search.text];
NSString * combined = [stringURL stringByAppendingString:stringSearch];
Instead of stringByAppendingString:, you could also use
NSString *combined = [NSString stringWithFormat: #"%#%#",
stringURL, stringSearch];
This is especially interesting/convenient if you have more than one string to append. Otherwise, the stringbyAppendingString: method is probably the better choice.
You can use stringByAppendingString:
stringURL = [#"http://www.websitehere.com/index.php?s="
stringByAppendingString:search.text];
If you want to have some control about the format of the parameter you should assemble
your URL string with
[NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text]
This solution is charming because you can append almost anything which can be inserted into a printf-style format.
I would not have given the answer of such general question.
There are many answers of same type question have already given. First find the answer of your question from existing question.
NSString* myURLString = [NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text];

How to concatenate two strings on iPhone?

How to connect string "Hello" and string "World" to "HelloWorld"? Looks like "+" doesn't work.
NSString *string = [NSString stringWithFormat:#"%#%#", #"Hello", #"World"];
NSLog(#"%#", string);
That should do the trick, although I am sure there is a better way to do this, just out of memory. I also must say this is untested so forgive me. Best thing is to find the stringWithFormat documentation for NSString.
How about:
NSString *hello = #"Hello";
NSString *world = #"World";
NSString *helloWorld = [hello stringByAppendingString:world];
If you have two literal strings, you can simply code:
NSString * myString = #"Hello" #"World";
This is a useful technique to break up long literal strings within your code.
However, this will not work with string variables, where you'd want to use stringWithFormat: or stringByAppendingString:, as mentioned in the other responses.
there's always NSMutableString..
NSMutableString *myString = [NSMutableString stringWithString:#"Hello"];
[myString appendString: #"World"];
Note:
NSMutableString *myString = #"Hello"; // won't work, literal strings aren't mutable
t3.text=[t1.text stringByAppendingString:t2.text];
Bill, I like yout simple solution and I'd like to note that you can also eliminate the space between the two NSStrings:
NSString * myString = #"Hello"#"World";