我想创建一个像这样的JSON
[{"phone":"3456345"}, {"phone":"2423242"}, {"phone":"2423423"}]
我有一个阵列,我只有电话号码。下面的代码将创建JSON,但为此我需要先创建字典。
contactData =[NSJSONSerialization dataWithJSONObject:contacts options:NSJSONWritingPrettyPrinted error:&error];
我试图像这样创建字典,但它只输入最后一个值,因为我不能为一个键设置重复值。请告诉我如何解决问题?
int i=0;
for (i=0; i<[all_contacts count]; i++)
{
[contacts setObject:[all_contacts objectAtIndex:i] forKey:@"phone"];
}
我如何在这里创建json。请告诉我?
答案 0 :(得分:3)
假设all_contacts
看起来像这样:
[ "3456345", "2423242", "2423423" ]
然后这应该有效:
NSMutableArray *root = [NSMutableArray new];
for (NSString *number in all_contacts) {
[root addObject:@{ "phone": number }];
}
contactData =[NSJSONSerialization dataWithJSONObject:root
options:NSJSONWritingPrettyPrinted
error:&error];
答案 1 :(得分:1)
int i=0;
NSMutableArray *contacts = [[NSMutableArray alloc] init];
for (i=0; i<[all_contacts count]; i++) {
[contacts addObject:@{@"phone" : [all_contacts objectAtIndex:i]}];
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contacts options:0 error:&error];
if (!jsonData) {
//error here
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}