JSON和动态TableView

时间:2013-02-22 13:41:40

标签: iphone objective-c json

任何人都可以向我提供可点击的tableview的JSON字符串的任何好例子吗?

我从服务器获取json字符串(已经工作),我需要用tableview发布视图。但它应该能够点击并给出该行的消息。 Json结构:

{ "messages":[{  
   "id": ....,  
   "msg":....,  
   "special":...,  
   "comments":...}]}

有什么好的例子吗?

3 个答案:

答案 0 :(得分:0)

我发现这段视频非常适合学习。

http://www.youtube.com/watch?v=9MEnvlqP-wU

同时检查我的一些问题,我问了很多关于JSON但是视频是向前发展的好方法。

更多链接:)

http://www.youtube.com/watch?v=YggsvQC2SH0

http://www.youtube.com/watch?v=RJZcD3hfs3k

答案 1 :(得分:0)

以下是您尝试执行的操作的代码。如果您愿意,可以修改为以不同方式查看,如果这是正确的,或者您正在寻找显示消息的其他方式,请允许我。

//
//  MyViewController.h
//  Test
//
//  Created by Syed Arsalan Pervez on 2/22/13.
//  Copyright (c) 2013 SAPLogix. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MyViewController : UITableViewController
{
    NSArray *_messages;
}

@end



//
//  MyViewController.m
//  Test
//
//  Created by Syed Arsalan Pervez on 2/22/13.
//  Copyright (c) 2013 SAPLogix. All rights reserved.
//

#import "MyViewController.h"

@interface MyViewController ()

@end

@implementation MyViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *JSONString = @"{\"messages\":[{\"id\":\"1\",\"msg\":\"Message Line\",\"special\":\"Special Line\",\"comments\":\"Comments Line\"},{\"id\":\"2\",\"msg\":\"Message Line\",\"special\":\"Special Line\",\"comments\":\"Comments Line\"}]}";

    NSError *error = nil;
    NSDictionary *JSONObj = [NSJSONSerialization JSONObjectWithData:[JSONString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
    if (!error)
    {
        _messages = [[JSONObj valueForKey:@"messages"] retain];
    }
    else
    {
        NSLog(@"Error: %@", error);
    }

    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return  3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    NSDictionary *_message = [_messages objectAtIndex:indexPath.section];
    switch (indexPath.row)
    {
        case 0:
            cell.textLabel.text = [_message valueForKey:@"msg"];
            break;

        case 1:
            cell.textLabel.text = [_message valueForKey:@"special"];
            break;

        case 2:
            cell.textLabel.text = [_message valueForKey:@"comments"];
            break;
    }
    _message = nil;

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *_message = [_messages objectAtIndex:section];
    return [NSString stringWithFormat:@"Message %@", [_message valueForKey:@"id"]];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *_message = [_messages objectAtIndex:indexPath.section];
    NSMutableString *string = [NSMutableString new];
    [string appendFormat:@"Message %@: ", [_message valueForKey:@"id"]];
    switch (indexPath.row)
    {
        case 0:
            [string appendString:[_message valueForKey:@"msg"]];
            break;

        case 1:
            [string appendString:[_message valueForKey:@"special"]];
            break;

        case 2:
            [string appendString:[_message valueForKey:@"comments"]];
            break;
    }
    _message = nil;

    [[[[UIAlertView alloc] initWithTitle:@"Alert" message:string delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] autorelease] show];
    [string release];
}

- (void)dealloc
{
    [_messages release];

    [super dealloc];
}

@end

输出:

enter image description here

答案 2 :(得分:-1)

您必须使用库解析该JSON响应,例如SBJson,然后从您的数据创建数组或字典,并使用此字典和数组填充您的tableview。

如果你能提供你的json响应,我可以帮助你解析它。

我是addind一些显示解析的代码片段:

SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];


            //to display driver name in drop down

            NSArray * messagesArray = [[NSArray alloc]init];
            messagesArray= [jsonData objectForKey:@"messages"];


            for(int i=0;i<[driverNameArray count];i++)
            {
                NSDictionary *tempDictionary = [messagesArray objectAtIndex:i];
                if([tempDictionary objectForKey:@"id"]!=nil)
                {

                    [idAry addObject:[tempDictionary objectForKey:@"id"]];

                }
                if([tempDictionary objectForKey:@"msg"]!=nil)
                {

                    [msgAry addObject:[tempDictionary objectForKey:@"msg"]];

                }
                if([tempDictionary objectForKey:@"special"]!=nil)
                {

                    [specialAry addObject:[tempDictionary objectForKey:@"special"]];

                }
                if([tempDictionary objectForKey:@"comments"]!=nil)
                {

                    [commentsAry addObject:[tempDictionary objectForKey:@"comments"]];

                }

            }

我使用过的所有数组commentsAry,specialAry,msgAry,idAry保存你的数据,并可用于填充tableview。