NSMutableArray到JSON对象

时间:2014-07-08 11:22:21

标签: ios json nsmutablearray nsjsonserialization

我有一个方法,我想返回一个NSData对象或一个'NSString',它必须是格式化的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'

2 个答案:

答案 0 :(得分:3)

您走在正确的轨道上,但您的键/值对被颠倒了。而是使用新的Objective-C字典文字语法,它更简单,更容易阅读,因此更容易发现错误:

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

编辑另外一个问题涉及使用描述数组(即字符串)而不是数组本身来创建JSON数据。它应该是:

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

答案 1 :(得分: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];