ios 将 JSON 数据的 NSString 转换为 NSArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17009877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting an NSString of JSON Data to NSArray
提问by Brandon
I have an NSStringthat is storing a JSONarray in the form of a NSString. The NSStringcalled colorArrayhas the value of:
我有一个NSString被存储JSON在的形式阵列NSString。被NSString调用colorArray的值为:
[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}];
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 tableDatainto an array like below, but I can't figure out how to convert the NSStringinto an array that can be used to populate the tableDatalike shown below...
我还有一个 tableview,我想将数组导入其中以填充表格。如果我将它加载tableData到如下所示的数组中,则该表有效,但我无法弄清楚如何将其NSString转换为可用于填充tableData如下所示的数组...
Anyone have ideas? Thanks much!
有人有想法吗?非常感谢!
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
tableData = [NSArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil];
}
回答by Martin R
// 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);
Output:
输出:
colorArray=[{ "color":"Red" },{ "color":"Blue" },{ "color":"Yellow"}]
jsonObject=(
{
color = Red;
},
{
color = Blue;
},
{
color = Yellow;
}
)
tableData=(
Red,
Blue,
Yellow
)
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.
最后一步使用的特殊功能-[NSArray valueForKey:]是返回一个数组,该数组包含valueForKey:使用每个数组对象上的键进行调用的结果。
回答by Anupdas
Try
尝试
- (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;
}
回答by lakesh
NSData * data = [colorArray dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];
NSArray *tableData = [JSON valueForKey:@"color"];
Hope this helps..
希望这可以帮助..
回答by hd1
Assuming you are using ios 5 or higher, JSON serialization is built in:
假设您使用的是ios 5 或更高版本,则内置了 JSON 序列化:
NSArray *json = [NSJSONSerialization
JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
Prior to ios5, you can use SBJSONto achieve the same:
在ios5之前,您可以使用SBJSON来实现相同的:
NSArray *jsonObjects = [jsonParser objectWithString:string error:&error];
回答by Manu
You just need to parse your tring in this way :
您只需要以这种方式解析您的字符串:
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];
after this you have an array of dictionay to get all the values you have to do loop the array and read each dictionary
在此之后,您有一个字典数组来获取您必须循环数组并读取每个字典的所有值
NSMutableArray *colorsArray = [NSMutableArray arrayWithCapacity:[jsonArray count]];
for (NSDictionary *colorDictionary in jsonArray) {
NSString *colorString = [colorDictionary objectForKey:@"color"];
[colorsArray addObject:colorString];
}
Now colorsArray is NSMutableArray like this :
现在 colorsArray 是 NSMutableArray 像这样:
[NSMutableArray arrayWithObjects:@"Red", @"Blue", @"Yellow", nil];
回答by Prateek Prem
If your data in coming from a webservice:
如果您的数据来自网络服务:
NSArray *tableData = [[NSJSONSerialization JSONObjectWithData:request.responseData options: NSJSONReadingMutableContainers error: &error] objectForKey:"yourKeyForColorArray"];

