2013-02-22 4 views
-1

Может ли кто-нибудь предоставить мне хороший пример строки JSON для интерактивного просмотра таблиц?JSON и динамический TableView

Я получаю строку json с задачами с сервера (уже работает), и мне нужно опубликовать его в представлении tableview. НО он должен иметь возможность щелкнуть и передать сообщение этой линии. Json structure:

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

Хорошие примеры?

+0

я не understad, вы хотите, чтобы заполнить ваш TableView со значением JSon? – Dilip

+0

Я хочу анализировать значение json для разных строк таблицы. И нажав строку таблицы, чтобы предупредить сообщение об этой строке –

ответ

0

Я нашел это видео очень полезным для обучения.

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

проверить Кроме того, некоторые из моих вопросов, я прошу много о JSON, но видео это хороший способ, чтобы двигаться вперед.

Больше ссылки :)

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

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

+0

У меня есть глупый вопрос. Будет ли это работать над версией iphone 4.2? :) –

+0

да, это зависит, если вам нужна помощь, просто разместите свой код, а другие помогут и объясните. Если это поможет, пожалуйста, отметьте правильный – Brent

-1

Вы должны проанализировать, что JSON ответ с использованием библиотеки, как SBJson, а затем создать массив или словарь из ваших данных и использовать этот словарь и массив для заполнения таблицы.

Если вы можете предоставить свой ответ 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.

+0

. Я предоставил вам возврат JSON. «...» означает, что он может вернуть (зависит от того, что находится в датаназе). сначала как id: 1, msg: test, special: 0, comments: 0 –

+0

Благодарим за помощь :) –

+0

У вас столько утечек, даже если вы используете ARC, попробуйте избежать бесполезного выделения. – SAPLogix

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

Смежные вопросы