Tuesday, August 02, 2011

Create JSON Object Manually without using SBJSON in iOS SDK

+(NSString *)createJSONString:(NSDictionary *) dictionary

{

NSArray *jsonKeyArray = [dictionary allKeys];

NSArray *jsonKeyValue = [dictionary allValues];

NSString *jsonString = @"{";

for (int j=0; j<[jsonKeyArray count ]; j++) {

NSDictionary *dictFromArray = [jsonKeyValue objectAtIndex:j];

NSArray *keyArray = [dictFromArray allKeys];

jsonString = [NSString stringWithFormat:@"%@\"%@\":",jsonString, [jsonKeyArray 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 != [jsonKeyArray 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 != [jsonKeyArray count]-1) {

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

}else

{

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

}

}

}

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

return jsonString;

}


2 comments:

andry said...

json is a very interesting language to be used. very good tutorial and can hopefully help me in building json in the application that I created for this lecture. thank you

EasytipsforCode said...

Andry thanks for your feedback !!!

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...