Create a JSON in Objective C
I want to create a JSON of this format
{"request": {
"longitude": 43.76,
"latitude": 12.34,
"category": [1,2,3],
"subCategory": [
{"subCatId": [1,2,3]},
{"subCatId": [1,2,3]}
]
}}
I am using the following code to create it
-(NSString*)populateUserPreferences
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *categoryId = [[NSMutableArray alloc] init];
NSMutableArray *subCategoryId = [[NSMutableArray alloc] init];
NSMutableDictionary *subCatDict = [[NSMutableDictionary alloc] init];
for (int i=0;i<开发者_StackOverflow中文版;10; i++)
{
[categoryId addObject:[NSNumber numberWithInt:i]];
}
for (int i=1; i<10; i++)
{
NSMutableArray *subCats = [[NSMutableArray alloc] init];
for (int j=0; j<i; j++)
{
[subCats addObject:[NSNumber numberWithInt:j]];
}
NSDictionary *subCatArray = [NSDictionary dictionaryWithObject:subCats forKey:@"subCatId"];
[subCatDict setDictionary:subCatArray];
[subCategoryId addObject:subCats];
[subCats release];
}
[dict setObject:[NSNumber numberWithFloat:12.3456] forKey:@"latitude"];
[dict setObject:[NSNumber numberWithFloat:72.2134] forKey:@"longitude"];
[dict setObject:categoryId forKey:@"category"];
[dict setObject:subCatDict forKey:@"subCategory"];
NSString * request = [dict JSONRepresentation];
NSLog(request);
NSDictionary *req = [NSDictionary dictionaryWithObject:dict forKey:@"request"];
return [req JSONRepresentation];
}
But in subcategory I am only getting entry from last loop. See below
{"request": {
"longitude":72.213401794433594,
"latitude":12.345600128173828,
"category":[0,1,2,3,4,5,6,7,8,9],
"subCategory": {
"subCatId":[0,1,2,3,4,5,6,7,8]
}
}}
Could someone please help me to create the reqired JSON string. Thanks
There's a line in your second for loop which overwrites subCatDict at each iteration.
for (int i=1; i<10; i++)
{
...
[subCatDict setDictionary:subCatArray];
...
}
I think what you actually want to use there is an array of dictionaries.
精彩评论