I’m trying to parse a very simple json object with 1 value. (ocUnit test below)
- (void) testHatCartParseWithValidRefId {
NSString* data = @"{\"refid\":999}";
Cart* obj = [HatCartParseJson parseJsonAndReturnObject:data];
STAssertTrue([obj.refid isEqualToString:@"999"], @"fail");
}
In the implementation everything fails when I add the line to pull it from either key or index. How should I pull this from the json input? Please keep in mind I need this json parse (not string) the actual code I’m working with is a large set of JSON data.
+ (Cart *) parseJsonAndReturnObject:(NSString *)json
{
NSArray* cart = [json JSONValue];
for (NSDictionary* item in cart) {
Cart* obj = [[Cart alloc] init];
//NSString* refid = [item objectAtIndex:0];
//NSString* refid = [item objectForKey:@"refid"];
[obj setRefid:@"999"];
return obj;
}
return nil;
}
Thank you in advance
You are expecting that the return value of
JSONValueis anNSArray, which in this case it isn’t.So, you must do a check if the return value is actually an
NSArray, and if it is, then iterate through the collection, otherwise check if it’s anNSDictionary, and if it is, then return theCartobject with therefidfrom theNSDictionary. If all of this fails, then just returnnil.As a side point, according to Apple’s Object Ownership Policy, you should return
autorelease-d objects from methods whose names do not contain the words “alloc”, “new” or “copy”. This would be one such method where you’d return anautorelease-d object.