0

I have a method where I want to return either an NSData object or an 'NSString' that must be a JSON object in format.

At the moment this is what I have;

-(NSData *)JSONData{

     NSMutableArray* arr = [NSMutableArray array];
     for (int j = 0; j < self.sales.subArray.count; j++)
     {
        SalesObject* subCategory = [self.sales.subArray objectAtIndex:j];


        NSDictionary * dict =[NSDictionary dictionaryWithObjectsAndKeys:
                                 @"category_id",subCategory.category_id,
                                 @"discounted",@"0",
                                 @"price",subCategory.price,
                                 @"active",subCategory.isActive, nil];
        NSLog(@"Dict %@",dict);

       [arr addObject:dict];

    }

    NSLog(@"Arr %@",arr);

   NSLog(@"Arr %@",arr);

   NSString *string = [arr description];
   NSData * jsonData = [NSJSONSerialization dataWithJSONObject:string options:kNilOptions error:nil];
   NSLog(@"JSON Data %@",jsonData);

   return jsonData;
}

As you can see I tried to convert an NSMutableArray to an NSData object but it didnt work. I get;

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary'

I now get the following error;

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
6
  • possible duplicate of Objective-C / iOS: Converting an array of objects to JSON string Commented Jul 8, 2014 at 11:26
  • what do you mean , but it didn't work.? That should be correct Commented Jul 8, 2014 at 11:29
  • @KumarKL I get ` Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary'` Commented Jul 8, 2014 at 11:32
  • create object of array using NSMutableArray* arr = [[NSMutableArray alloc] init]; Commented Jul 8, 2014 at 11:32
  • What's the log of NSLog(@"Arr %@",arr);? Commented Jul 8, 2014 at 11:33

2 Answers 2

3

You are on the right track, but you have your key/value pairs reversed. Instead use the new Objective-C dictionary literal syntax, which is shorter and easier to read, and therefore easier to spot mistakes:

NSDictionary *dict = @{
    @"category_id" : subCategory.category_id,
    @"discounted"  : @"0",       // Should that be @(0) ???
    @"price"       : subCategory.price,
    @"active"      : subCategory.isActive
};

EDIT The additional problem relates to the use the description of the array (i.e. a string), rather than the array itself, being used to create the JSON data. It should be:

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr
                                                   options:kNilOptions
                                                     error:&error];
if (!jsonData) {
    NSLog(@"Achtung!  Failed to create JSON data: %@", [error localizedDescription]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good caught the mistake .
Thanks for that!! However know I get another error. I believe I am on the right track also. Please see above
0

Change the dictionary definition from

 NSDictionary * dict =[NSDictionary dictionaryWithObjectsAndKeys:
                             @"category_id",subCategory.category_id,
                             @"discounted",@"0",
                             @"price",subCategory.price,
                             @"active",subCategory.isActive, nil];

to

NSDictionary * dict =[NSDictionary dictionaryWithObjectsAndKeys:
                             subCategory.category_id,@"category_id",
                             @"0", @"discounted",
                             subCategory.price,@"price",
                             subCategory.isActive, @"active", nil];

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.