Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONKit: create a json formatted string

Tags:

json

ios

I want to convert NSDictionary's and NSArrays to json format. Can JSON Kit do that and how?

like image 333
António Avatar asked Jul 18 '11 16:07

António


2 Answers

// data->string

NSMutableDictionary *nameElements = [NSMutableDictionary dictionary];     

[nameElements setObject:@"abcd" forKey:@"username"];

[nameElements setObject:@"1234" forKey:@"password"];    

NSString* jsonString = [nameElements JSONString];  

// string->data

NSDictionary *nameElements_ = [jsonString objectFromJSONString];   

for(NSString *key in [nameElements_ allKeys]) {
    NSString* body = [nameElements_ objectForKey:key];
    NSLog(@"%@", body);
}
like image 82
Andy Lee Avatar answered Oct 13 '22 02:10

Andy Lee


This is an example of sending dictionary and array to server.which worked for me 1000000% .

SBJSON *jparser = [[SBJSON new] autorelease];


NSString *ArrayjsonItems = [jparser stringWithObject:self.UrMergedArray];

NSString *DicjsonItems = [jparser stringWithObject:self.UrMergedDic];




NSLog(@"array Items :%@",self.UrMergedArray);

NSLog(@"dic Items :%@",self.UrMergedDic);




NSString *postString =[NSString stringWithFormat:@"Arrayitems=%@&Dicitems=%@",ArrayjsonItems,DicjsonItems];


NSLog(@"it is going to post : %@ \n\n",postString);



NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:snapURL];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];



NSURLConnection *connection=[[NSURLConnection alloc]
                             initWithRequest:request
                             delegate:self];


if (connection) {

    self.receivedData = [[NSMutableData data] retain];

}


[connection release];   
like image 32
Vijay-Apple-Dev.blogspot.com Avatar answered Oct 13 '22 00:10

Vijay-Apple-Dev.blogspot.com