Convert 2D NSMutableArray in JSON format - JSONKit
I have the following array
NSMutableArray* answers;
Each element of answers is itself an array of objects.
I need to convert the above 2D array into appropriate JSON format (using the JSONKit framework), so that it can be passed to a php application and decoded t开发者_运维知识库hereafter...
The individual objects have the following structure:
@interface Answer : NSObject {
//NSString* answerId;
NSString* answer;
NSString* questionId;
}
//@property (nonatomic, retain) NSString* answerId;
@property (nonatomic, retain) NSString* answer;
@property (nonatomic, retain) NSString* questionId;
@end
That is that each element of answers is an array of Answer Objects. essentially what I need is to encode the relevant data in each answer object into JSON format using the JSONKit framework so that it can be posted to a php app and decoded....
Essentially I need somthing of the form:
{{"answer":"1","questionId":"1"}, {{"answer":"5","questionId":"2"},......}
The JSONKit, like all other JSON frameworks, does not play well with custom objects. To that end, you need to iterate through your object and put them into objects that the JSONKit can understand (NSArrays and NSDictionaries). Something like this:
NSMutableArray *jAnswers = [[[NSMutableArray alloc] init] autorelease];
for(Answer *answ in answers)
{
NSMutableDictionary *jAnswer = [[[NSMutableDictionary alloc] init] autorelease];
[jAnswer addObject: answ.answer forKey: @"answer"];
[jAnswer addObject: answ.questionId forKey: @"questionId"];
[jAnswers addObject: jAnswer];
}
NSString *jAnswersJSONFormat = [jAnswers JSONString];
would give you:
[{"answer": "1", "questionId": "1"}, {"answer": "5", "questionId": "2"}, ...]
JSONKit
does seem to offer both a delegate-based and a block-based method for serializing unsupported object types. My guess, not having used the framework, is that you call one of those versions of the serialization methods and pass a delegate/selector pair or a block which returns a JSON-serializable object in place of an unsupported object type.
You'll want one of these category methods on NSArray
:
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
精彩评论