2

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 thereafter...

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"},......}

2 Answers 2

5

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"}, ...]
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.