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'
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 (ie 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]);
}
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.