Создать JSON в Objective C - PullRequest
       6

Создать JSON в Objective C

3 голосов
/ 28 июня 2011

Я хочу создать JSON этого формата

{"request": {
  "longitude": 43.76,
  "latitude": 12.34,
  "category": [1,2,3],
  "subCategory": [
    {"subCatId": [1,2,3]},
    {"subCatId": [1,2,3]}
  ]
}}

Я использую следующий код для его создания

-(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<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];
}

Но в подкатегории я получаю запись только из последнего цикла,См. Ниже

{"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]
  }
}}

Может кто-нибудь помочь мне создать нужную строку JSON.Спасибо

1 Ответ

2 голосов
/ 28 июня 2011

В вашем втором цикле for есть строка, которая перезаписывает subCatDict на каждой итерации.

for (int i=1; i<10; i++) 
{
   ...
   [subCatDict setDictionary:subCatArray];
   ...
}

Я думаю, что вы действительно хотите использовать есть массив словарей.

...