2011-06-28 49 views
3

我要創建這種格式的JSON創建目標C一個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] 
    } 
}} 

有人可以請幫助我創建reqired JSON字符串。 謝謝

+0

您的縮進使得它有點難以閱讀。我可以建議把大括號放在'for'語句的同一行。 –

+0

你知道有很多第三方的對象,例如JSONKit,是嗎? (在iOS5中,蘋果提供它自己的) – codeclash

回答

2

你的第二個循環會在每次迭代中覆蓋subCatDict。

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

我想你實際上想要使用的是一個字典數組。

+1

您的回覆*字典數組*幫助我也將所需的JSON重寫爲xcode生成的格式。還有,我也加了一個upmark。 – Zach