gpt4 book ai didi

iphone - 在 Objective C 中创建一个 JSON

转载 作者:搜寻专家 更新时间:2023-10-30 20:22:34 24 4
gpt4 key购买 nike

我想创建一个这种格式的 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];
...
}

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

关于iphone - 在 Objective C 中创建一个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6511796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com