从nsmutablearray创建一系列json字符串

时间:2016-07-11 07:43:26

标签: ios objective-c

我使用以下代码从数组创建一个json字符串。

for (int k = 0 ; k < [[self totalCompliancesCount] count]; k++) {
        delayedJsonObject = [[NSMutableDictionary alloc]init];
        [delayedJsonObject setValue:[[self totalCompliancesCount] objectAtIndex:k] forKey:@"t"];
        [delayedJsonObject setValue:[[self totalCompliedCompliancesCount] objectAtIndex:k] forKey:@"y"];
        delayedJsonData = [NSJSONSerialization dataWithJSONObject:delayedJsonObject options:0 error:nil];
        delayedJsonString = [[NSString alloc] initWithBytes:[delayedJsonData bytes] length:[delayedJsonData length] encoding:NSUTF8StringEncoding];

    }

[[self totalCompliancesCount] count]是6.所以delayedJsonString必须包含6个jsonobjects,但它只包含最后一个json对象。 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您有效地重新创建循环的每次迭代delayedJsonString而不是追加到最后。

尝试类似:

NSMutableString *delayedJsonString = @"".mutableCopy;
for (int k = 0 ; k < [[self totalCompliancesCount] count]; k++) {
    delayedJsonObject = [[NSMutableDictionary alloc]init];
    [delayedJsonObject setValue:[[self totalCompliancesCount] objectAtIndex:k] forKey:@"t"];
    [delayedJsonObject setValue:[[self totalCompliedCompliancesCount] objectAtIndex:k] forKey:@"y"];
    delayedJsonData = [NSJSONSerialization dataWithJSONObject:delayedJsonObject options:0 error:nil];
    [delayedJsonString appendString:[[NSString alloc] initWithBytes:[delayedJsonData bytes] length:[delayedJsonData length] encoding:NSUTF8StringEncoding]];        
}

答案 1 :(得分:0)

您需要将此行移到循环之外:

delayedJsonObject = [[NSMutableDictionary alloc]init]; 

答案 2 :(得分:0)

如果我正确地得到你的问题,你想要一个基于对象列表的字符串。

也许你可以尝试这样的事情:

NSMutableArray *delayedJsonObjectList = [NSMutableArray new];
for (int k = 0 ; k < [[self totalCompliancesCount] count]; k++) {
    delayedJsonObject = [[NSMutableDictionary alloc]init];
    [delayedJsonObject setValue:[[self totalCompliancesCount] objectAtIndex:k] forKey:@"t"];
    [delayedJsonObject setValue:[[self totalCompliedCompliancesCount] objectAtIndex:k] forKey:@"y"];   
    [delayedJsonObjectList addObject:delayedJsonObject];
}
NSError *error = nil;
NSData *delayedJsonData = [NSJSONSerialization dataWithJSONObject:delayedJsonOjbectList options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:delayedJsonData encoding:NSUTF8StringEncoding];

刚才刚刚鞭打它还没有测试它。将在测试后更新

OUTPUT :(假设数据)

[{ “T”:1, “y” 的:2},{ “T”:1, “y” 的:2},{ “T”:1, “y” 的:2},{ “t” 的:1, “y” 的:2} ..]