#ios
NSMutableDictionary 是比较灵活的字典结构,完成初始化后,搭配 setObject 和 forKey 的方式,完成数据的添加;
需要注意的是,NSMutableDictionary是一个结构灵活复杂的容器,其中可能包含,其他复杂子结构,例如日期、数组队列、枚举,其他字典等;
在转字符串之前,需要先将,其他复杂子结构,完成字符串的数据转换,参考[[ios NSArray转字符串]] 和 [[ios日历转字符串]]和[[ios枚举转字符串]];
在完成数据的填充后,通过 copy 的方式,完成从 NSMutableDictionary 到 NSDictionary 的转换
代码示例:
NSMutableDictionary *questionResponsesDict = [NSMutableDictionary dictionary];
for(NSUInteger i=0;i<[respondent.questionResponses count]-1;i++)
{
SMQuestionResponse *questionResponse = respondent.questionResponses[i];
NSMutableDictionary *stringDict = [NSMutableDictionary dictionary];
[stringDict setObject:questionResponse.pageID forKey:@"pageID"];
[stringDict setObject:questionResponse.questionID forKey:@"questionID"];
[stringDict setObject:questionResponse.questionValue forKey:@"questionValue"];
[stringDict setObject:[questionResponse.answers description] forKey:@"answers"];
NSNumber *pageIndexNumber = @(questionResponse.pageIndex);
NSString *pageIndexString = [pageIndexNumber stringValue];
[stringDict setObject:pageIndexString forKey:@"pageIndex"];
NSNumber *questionSurveyIndexNumber = @(questionResponse.questionSurveyIndex);
NSString *questionSurveyIndexString = [questionSurveyIndexNumber stringValue];
[stringDict setObject:questionSurveyIndexString forKey:@"questionSurveyIndex"];
NSNumber *questionPageIndexNumber = @(questionResponse.questionPageIndex);
NSString *questionPageIndexString = [questionPageIndexNumber stringValue];
[stringDict setObject:questionPageIndexString forKey:@"questionPageIndex"];
NSDictionary *nsDict = [stringDict copy];
NSNumber *index = @(i);
NSString *indexString = [index stringValue];
[questionResponsesDict setObject:nsDict forKey:indexString];
}
然后,通过 NSJSONSerialization dataWithJSONObject 的方式,完成从字典,到NSData 数据类的,格式转换;
其中 options:0 指的是,会去掉 json 数据体 换行符等格式信息;
最后,再配合 encoding:NSUTF8StringEncoding 编码格式,完成字符串的转换即可
NSDictionary *finalResponseDict = [questionResponsesDict copy];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalResponseDict options:0 error:&error];
if (error) {
NSLog(@"Error converting dictionary to JSON: %@", error.localizedDescription);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(@"%@", jsonString);
}