【发布时间】:2014-07-08 11:22:20
【问题描述】:
我有一个方法,我想返回 NSData 对象或格式必须是 JSON 对象的“NSString”。
目前这就是我所拥有的;
-(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'
【问题讨论】:
-
你是什么意思,但它不起作用。?那应该是正确的
-
@KumarKL 我得到`由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'JSON字典中的无效(非字符串)键'`
-
使用 NSMutableArray* 创建数组对象 arr = [[NSMutableArray alloc] init];
-
NSLog(@"Arr %@",arr);的日志是什么?
标签: ios json nsmutablearray nsjsonserialization