繁体   English   中英

在目标 C 中创建 JSON

[英]Create a JSON in Objective 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]
  }
}}

有人可以帮我创建所需的 JSON 字符串。 谢谢

第二个 for 循环中有一行在每次迭代时覆盖 subCatDict 。

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

我认为您真正想要使用的是一系列字典。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM