我有一個方法,我想返回一個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