【问题标题】:Converting an NSString of JSON Data to NSArray [closed]将 JSON 数据的 NSString 转换为 NSArray [关闭]
【发布时间】:2013-06-09 13:03:07
【问题描述】:

我有一个NSString,它以NSString 的形式存储JSON 数组。名为colorArrayNSString 的值为:

[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}];

我还有一个表格视图,我想将数组导入其中以填充表格。如果我将tableData 加载到如下所示的数组中,则该表有效,但我不知道如何将NSString 转换为可用于填充tableData 的数组,如下所示...

有人有想法吗?非常感谢!

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data
    tableData = [NSArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil];
}

【问题讨论】:

  • -1 第1000次询问如何将JSON转换为NSArray
  • 我认为它隐式地将 if 转换为字符串?

标签: ios objective-c iphone json


【解决方案1】:
// Your JSON data:
NSString *colorArray = @"[{ \"color\":\"Red\" },{ \"color\":\"Blue\" },{ \"color\":\"Yellow\"}]";
NSLog(@"colorArray=%@", colorArray);

// Convert to JSON object:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[colorArray dataUsingEncoding:NSUTF8StringEncoding]
                                                      options:0 error:NULL];
NSLog(@"jsonObject=%@", jsonObject);

// Extract "color" values:
NSArray *tableData = [jsonObject valueForKey:@"color"];
NSLog(@"tableData=%@", tableData);

输出:

colorArray=[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}] json对象=( { 颜色=红色; }, { 颜色=蓝色; }, { 颜色=黄色; } ) 表数据=( 红色的, 蓝色的, 黄色的 )

最后一步使用-[NSArray valueForKey:]的特殊功能 它返回一个数组,其中包含使用每个数组对象上的键调用 valueForKey: 的结果。

【讨论】:

  • 谢谢马丁,我会检查一下。 NSString 是否需要包含斜杠才能使转换正常工作?再次感谢!
  • @Brandon:反斜杠只是将示例输入定义为示例代码中的字符串常量所必需的。
  • @Brandon:我添加了一些 NSLog 输出来阐明这些步骤。
【解决方案2】:

试试

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *jsonString = ...//String representation of json 
    NSData *jsonData =  [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    //colors is a NSArray property used as dataSource of TableView
    self.colors = [NSJSONSerialization JSONObjectWithData:jsonData
                                                  options:NSJSONReadingMutableContainers
                                                    error:nil];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.colors count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *color = self.colors[indexPath.row];
    cell.textLabel.text = color[@"color"];

    return cell;
}

【讨论】:

    【解决方案3】:
    NSData * data = [colorArray dataUsingEncoding:NSUTF8StringEncoding]
    NSDictionary *JSON = 
        [NSJSONSerialization JSONObjectWithData: data
                                        options: NSJSONReadingMutableContainers 
                                          error: &e];
    
    NSArray *tableData = [JSON valueForKey:@"color"];
    

    希望这会有所帮助..

    【讨论】:

      【解决方案4】:

      假设您使用的是ios 5 or higher,则内置JSON序列化:

      NSArray *json = [NSJSONSerialization 
              JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
              options:kNilOptions 
              error:&error];
      

      在ios5之前,你可以使用SBJSON来实现同样的效果:

      NSArray *jsonObjects = [jsonParser objectWithString:string error:&error];
      

      【讨论】:

        【解决方案5】:

        你只需要以这种方式解析你的字符串:

        NSString *jsonString = @"[{\"color\":\"Red\" },{\"color\":\"Blue\" },{\"color\":\"Yellow\"}]";
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSError *error = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        

        在此之后,你有一个字典数组来获取你必须循环数组并读取每个字典的所有值

        NSMutableArray *colorsArray = [NSMutableArray arrayWithCapacity:[jsonArray count]];
        
        for (NSDictionary *colorDictionary in jsonArray) {
        
            NSString *colorString = [colorDictionary objectForKey:@"color"];
            [colorsArray addObject:colorString];
        }
        

        现在 colorsArray 是这样的 NSMutableArray :

         [NSMutableArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil];
        

        【讨论】:

          【解决方案6】:

          如果您的数据来自网络服务:

          NSArray *tableData = [[NSJSONSerialization JSONObjectWithData:request.responseData options: NSJSONReadingMutableContainers error: &error] objectForKey:"yourKeyForColorArray"];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-10-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-31
            • 2020-09-21
            相关资源
            最近更新 更多