将JSON数据的NSString转换为NSArray [英] Converting an NSString of JSON Data to 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屋!