将JSON数据的NSString转换为NSArray [英] Converting an NSString of JSON Data to NSArray

查看:65
本文介绍了将JSON数据的NSString转换为NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an NSString that is storing a JSON array in the form of a NSString. The NSString called colorArray has the value of:

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

我还有一个tableview,我想导入数组以填充表格。如果我将 tableData 加载到如下所示的数组中,该表有效,但我无法弄清楚如何转换 NSString 进入一个可用于填充 tableData 的数组,如下所示......

I also have a tableview that I would like to import the array into in order to populate the table. The table works if I load the tableData into an array like below, but I can't figure out how to convert the NSString into an array that can be used to populate the tableData like shown below...

任何人都有想法?非常感谢!

Anyone have ideas? Thanks much!

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


推荐答案

// 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"}]
jsonObject=(
        {
        color = Red;
    },
        {
        color = Blue;
    },
        {
        color = Yellow;
    }
)
tableData=(
    Red,
    Blue,
    Yellow
)

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

The last step uses the special feature of -[NSArray valueForKey:] that returns an array containing the results of invoking valueForKey: using the key on each of the array's objects.

这篇关于将JSON数据的NSString转换为NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆