2014-07-08 143 views
0

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

的可能重複的[目標C/iOS的:轉換對象的數組到JSON字符串]( http://stackoverflow.com/questions/9139454/objective-c-ios-converting-an-array-of-objects-to-json-string) – Mrunal

+0

你是什麼意思,**但它沒有工作** 。?這應該是正確的 –

+0

@KumarKL我得到終止應用程序由於未捕獲的異常'NSInvalidArgumentException',原因:'JSON字典'中的'無效(非字符串)鍵' – DevC

回答

3

您處於正確的軌道上,但您已將您的鍵/值對顛倒過來。代替使用新的目標C辭典文字語法,這是更短和更容易閱讀,並且因此更容易發現錯誤:

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

EDIT附加問題涉及使用該陣列的描述(即字符串),而不是數組本身,用於創建JSON數據。它應該是:

NSError *error = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr 
                options:kNilOptions 
                error:&error]; 
if (!jsonData) { 
    NSLog(@"Achtung! Failed to create JSON data: %@", [error localizedDescription]); 
} 
+2

好抓住了錯誤。 –

+0

謝謝!但是知道我得到另一個錯誤。我相信我也處於正確的軌道上。請看上面的 – DevC

0

更改字典的定義從

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

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

是的,那看起來好多了...... – trojanfoe