gpt4 book ai didi

ios - 在 iOS 中创建 JSON 格式

转载 作者:行者123 更新时间:2023-11-29 02:55:22 25 4
gpt4 key购买 nike

我有两个以JSON格式向服务器发送数据,以下是服务器需要的格式

{
"employees": [
{ "firstName":"John" "middelName":"M" "lastName":"Doe" },
{ "firstName":"Anna" "middelName":"J" "lastName":"Smith" },
{ "firstName":"Peter" "middelName":"K" "lastName":"Jones" }
]
}

现在我有三个 NSMutableArrays ,第一个数组包含firstName,第二个数组包含middleName,第三个数组包含lastName,

如果它只是一条记录,我可以这样创建它

NSDictionary *dictionary = @{@"employees": @{@"firstName":"John" "middelName":"M" "lastName":"Doe"}};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
}

现在我对如何创建记录数组感到困惑

最佳答案

尝试这样的事情:

/* assuming the arrays have equal length, no error checking */
NSMutableArray * employees = [NSMutableArray new];
NSUInteger idx = 0;
for(NSString * firstName in firstNames) {
[employees addObject:@{
@"firstName":firstName,
@"middleName":[middleNames objectAtIndex:idx],
@"lastName":[lastNames objectAtIndex:idx]
}];
idx++;
}
id sendThis = @{@"employees": employees};
/* do your JSON stuff with sendThis */

关于ios - 在 iOS 中创建 JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967655/

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