I have an NSMutableArray that holds a collection of objects, with each object having three parameters of type NSString. What I need to do is iterate through this collection, and create a single JSON document with two subsections: one is called "Test Results", the other is called, "Reports". Each object in the NSMutable array has three NSString parameters, and one of these parameters is called, "testResult".
If "testResult" has a value of either "pass" or "fail", then that object needs to go into the "Test Result" section. If the parameter has a value of "na", then the object goes into the "Reports" section. The "Test Results" section should have three "elements": "Name", "Date", "Test Result". The "Reports" section needs to have only two elements: "Name", and "Date". My issue is not how to iterate through an NSMutableArray using a for loop, my issue is how to iterate through an NSMutableArray, and construct a JSON document as I have described above.
My code would be something like:
//creating beginning of JSON document here
for (Person *personObject in testResultArray) {
if (personObject.testResult == @"na") {
//construct JSON object for "Reports" section
NSString *jsonString1 = personObject.name;
NSString *jsonString2 = personObject.date;
NSData *data1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json1 = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:&error];
id json2 = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:&error];
}
else {
//construct JSON object for "Test Results" section
NSString *jsonString1 = personObject.name;
NSString *jsonString2 = personObject.date;
NSString *jsonString3 = personObject.testResult;
NSData *data1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data3 = [jsonString3 dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json1 = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:&error];
id json2 = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:&error];
id json3 = [NSJSONSerialization JSONObjectWithData:data3 options:0 error:&error];
}
}
//close the JSON document construction, and return JSON document.