Powered By Blogger

Wednesday, March 21, 2012

Create JSON without using SBJSON

Hello every one,
This one is to create simple json format without using JSON framework.  This one is just example not a replacement for JSON framework.


+(NSString *)createJSONString:(NSDictionary *) dictionary
{
NSArray *jsonKeys = [dictionary allKeys];
NSArray *jsonKeyValues = [dictionary allValues];

NSString *jsonString = @"{";

for (int j=0; j<[jsonKeys count ]; j++) {
 
NSDictionary *dictFromArray = [jsonKeyValues objectAtIndex:j];
NSArray *keyArray = [dictFromArray allKeys];
jsonString = [NSString stringWithFormat:@"%@\"%@\":",jsonString, [jsonKeys objectAtIndex:j]];
NSArray *valueArray = [dictFromArray allValues];
// to check its empty dictionary
if ([keyArray count] != 0) {
for (int i = 0; i<[keyArray count];i++) {
if (i == 0) {
jsonString =[NSString stringWithFormat:@"%@{ \"%@\": \"%@\", ",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];
}//to check lost element of single dictionary
else if((i == [keyArray count]-1) ) {
if (j != [jsonKeys count]-1) {
// to check whether last element combined dictionary
jsonString =[NSString stringWithFormat:@" %@ \"%@\":\"%@\" },",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];
}else
{
jsonString =[NSString stringWithFormat:@" %@ \"%@\":\"%@\" }",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];
}
}else {
jsonString =[NSString stringWithFormat:@"%@ \"%@\":\"%@\", ",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];
}
}
}else {
  
if (j != [jsonKeys count]-1) {
jsonString =[NSString stringWithFormat:@"%@{},",jsonString];
}else
{
jsonString =[NSString stringWithFormat:@"%@{}",jsonString];
   
}
}
}

jsonString =[NSString stringWithFormat:@"%@ }",jsonString];

return jsonString;
}


If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

No comments:

Post a Comment