0

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

Community
  • 1
  • 1
baste
  • 827
  • 2
  • 9
  • 18

3 Answers3

6

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"}}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
5

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".

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • how to do this inside nsdictionary – baste Jan 21 '13 at 11:35
  • As i mentioned in my answer, you **CAN NOT** you need to use some special character like space or something else, but that will also come with " & ". – Anoop Vaidya Jan 21 '13 at 11:41
  • If there is some hack then I am waiting for the solution. – Anoop Vaidya Jan 21 '13 at 11:42
  • I tried this one, but also failed : NSString *quotedProfile=[NSString stringWithFormat:@"\"%@\"",@"Profile"]; NSString *ename=@"John Doe"; NSDictionary *profile=@{@"Profile":@{@"Name":ename}}; // I need to display like this "Profile":{"Name":"John Doe"} NSLog(@"-> %@",profile); – Anoop Vaidya Jan 21 '13 at 11:42
  • thank you for your time AKV definitely there is a solution for here, i have a variable that needs to be in dictionary and send as json – baste Jan 21 '13 at 11:50
  • Check my update... What solution you got? that one in my comment? – Anoop Vaidya Jan 21 '13 at 11:52
  • 1
    just an idea but not yet tested, i will use like this NSString *X =[NSString stringWithFormat:@"%@", ename]; – baste Jan 21 '13 at 12:08
  • and remember as you are using one special character(") for key, the description method will add extra quotes for you, so you will end up with more quotes than you actually required. – Anoop Vaidya Jan 21 '13 at 12:11
1

Check this

NSString *string=@"This is test \" for \"";

Hope it helps you..

P.J
  • 6,547
  • 9
  • 44
  • 74