【问题标题】:how to Filter the Json data in ios objective c如何在ios目标c中过滤Json数据
【发布时间】:2016-08-29 08:13:04
【问题描述】:

JSON 解析有问题。
我得到 JSON 数据,我想显示与 restid 匹配的项目。
我有一个 tableView 来显示不同的餐厅信息,每家餐厅也有自己的评论单元来评论这家餐厅。
所以,我会过滤 JSON 数据。
让每个餐厅评论单元都能获得自己的评论。

这是我的 JSON:

(
    {
    comment = "very good";
    food = chicken;
    name = Tom;
    restid = 1;
    score = 4;
},
    {
    comment = nice;
    food = coffee;
    name = Jack;
    restid = 3;
    score = 3;
},
    {
    comment = tasty;
    food = pizza;
    name = Mary;
    restid = 17;
    score = 5;
},
    {
    comment = unlike;
    food = none;
    name = Gigi;
    restid = 33;
    score = 1;
},
    {
    comment = delicious;
    food = juice;
    name = Bruce;
    restid = 45;
    score = 5;
}
)

这是我的代码:

它可以显示我的 tableView 中的所有数据以及不同餐厅评论单元中的所有相同数据。

- (void)getCommentInfo:(id)sender {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:@"http://localhost:8888/foodComment_json.php"];

        NSData *data = [NSData dataWithContentsOfURL:url];
        NSArray *comment = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"Comment is %@",comment);

        self.commentArray = [NSMutableArray arrayWithArray:comment];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.detailCommentTableView reloadData];
        });
    });
}

【问题讨论】:

  • 使用NSPredicate
  • 感谢您的帮助。

标签: ios objective-c iphone json


【解决方案1】:

试试这个,我没有测试代码所以如果你有问题请告诉我。

NSArray *filteredArray = [comment filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id elem, NSDictionary *bindings) {
    return ([elem objectForKey:@"restid"] == <your_rest_id>)
}]];

【讨论】:

    【解决方案2】:

    你可以这样做

     NSArray *array = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"<filter string?" forKey:@"restid"]];   // you can also do same for Name key... 
     NSArray *filteredarray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(restid == %@)", @"<filter string>"]];
    

    【讨论】:

    • 谢谢您的回答。帮了我很多忙。
    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2013-11-30
    • 2019-08-17
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多