我正在从一个 NSMutableDictionary 生成一个 JSON 文档,该文档由指向 NSStrings 的键以及依次指向其他 NSMutableDictionary 的两个键组成。我的问题是,当我输出 JSON 文档时,我注意到 JSON 文档具有我以不同顺序插入到 NSMutableDictionary 中的对象。例如,我目前的输出如下所示:
JSON Output: {
"devicetype" : "iPhone Simulator",
"os" : "6.0",
"test_results" : [
{
"date" : "2012-12-25T20:38:09",
"name" : "Test 1",
"result" : "Fail"
},
{
"date" : "2012-12-25T20:38:11",
"name" : "Test 2",
"result" : "Pass"
},
{
"date" : "2012-12-25T20:38:13",
"name" : "Test 3",
"result" : "Pass"
},
{
"date" : "2012-12-25T20:38:19",
"name" : "Test 4",
"result" : "Fail"
}
],
"devicename" : "?????",
"reports" : [
],
"device_id" : "bb88413b178b4ef77830d385b9a4bd6d",
"platform" : "iPhone OS"
}
但我希望输出看起来像这样:
JSON Output: {
"devicetype" : "iPhone Simulator",
"os" : "6.0",
"devicename" : "?????",
"device_id" : "bb88413b178b4ef77830d385b9a4bd6d",
"platform" : "iPhone OS"
"test_results" : [
{
"date" : "2012-12-25T20:38:09",
"name" : "Test 1",
"result" : "Fail"
},
{
"date" : "2012-12-25T20:38:11",
"name" : "Test 2",
"result" : "Pass"
},
{
"date" : "2012-12-25T20:38:13",
"name" : "Test 3",
"result" : "Pass"
},
{
"date" : "2012-12-25T20:38:19",
"name" : "Test 4",
"result" : "Fail"
}
],
"reports" : [
],
}
我拥有的用于创建 JSON 文档的代码如下所示:
NSMutableArray* reports = [NSMutableArray array];
NSMutableArray* results = [NSMutableArray array];
for (TestResult *testObject in testResultArray) {
if ([[DataModel sharedInstance] getScore:testObject.score] == @"Not Tested") {
NSMutableDictionary *naTest = [NSMutableDictionary dictionary];
[naTest setObject:testObject.testName forKey:@"name"];
[naTest setObject:testObject.dateStamp forKey:@"date"];
[reports addObject:naTest];
}
else {
NSMutableDictionary *fullTest = [NSMutableDictionary dictionary];
NSString *score = [[DataModel sharedInstance] getScore:testObject.score];
[fullTest setObject:score forKey:@"result"];
[fullTest setObject:testObject.testName forKey:@"name"];
[fullTest setObject:testObject.dateStamp forKey:@"date"];
[results addObject:fullTest];
}
}
NSMutableDictionary *mainDoc = [NSMutableDictionary dictionary];
[mainDoc setObject:udid forKey:@"device_id"];
[mainDoc setObject:systemName forKey:@"platform"];
[mainDoc setObject:systemVersion forKey:@"os"];
[mainDoc setObject:@"?????" forKey:@"devicename"];
[mainDoc setObject:deviceType forKey:@"devicetype"];
[mainDoc setObject:results forKey:@"test_results"];
[mainDoc setObject:reports forKey:@"reports"];
NSError *ierror = nil;
NSData *jsnData = [NSJSONSerialization dataWithJSONObject:mainDoc options:NSJSONWritingPrettyPrinted error:&ierror];
NSString *jsnString = [[NSString alloc] initWithData:jsnData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsnString);
}
我的另一个担心是 test_results 的输出也没有按照我想要的顺序出现。它们按“日期”、“名称”、“结果”的顺序出现,我希望输出为“名称”、“日期”、“结果”。有没有办法我也可以纠正这个订单?