我有一个方法,我想返回一个NSData
对象或一个'NSString',它必须是格式的JSON对象。NSMutableArray到JSON对象
目前这是我的;
-(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;
}
正如你可以看到我尝试了NSMutableArray
转换为NSData
对象,但它没有工作。我得到;
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary'
我现在碰到下面的错误;
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
的可能重复的[目标C/iOS的:转换对象的数组到JSON字符串]( http://stackoverflow.com/questions/9139454/objective-c-ios-converting-an-array-of-objects-to-json-string) – Mrunal
你是什么意思,**但它没有工作** 。?这应该是正确的 –
@KumarKL我得到终止应用程序由于未捕获的异常'NSInvalidArgumentException',原因:'JSON字典'中的'无效(非字符串)键' – DevC