+(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:
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
Andry thanks for your feedback !!!
Post a Comment