在iOS中创建JSON格式

时间:2014-05-31 07:38:09

标签: ios json nsjsonserialization

我有两个以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]);
    }

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

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

/* 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 */

答案 1 :(得分:0)

[] --->数组,{} - >字典

编码可以是这样的(只是一个例子)

NSArray *local_array = @[@{@"f":@"ew",@"d":@"new"}];

NSDictionary *dictionary = @{@"employees": local_array};