Genevios
Genevios

Reputation: 1145

How to choose key for JSON in xCode

I have one JSON and two controller. So my JSON have keys: News, TitleNews, number of news for example one or two and others. So one of the string of my parse code:

In the first ViewController with UITableView

NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:@"data"];

and also in tableView:

cell.textLabel.text = [[array objectAtIndex:indexPath.row]objectForKey:@"title"];

and also prepareForSegue

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UITableViewCell *cell = (UITableViewCell*)sender;
    NSIndexPath *indexPath = [self.tableTrack indexPathForCell:cell];
    NSDictionary *newsData = [array objectAtIndex:indexPath.row];
    WebController *vc = (WebController*)segue.destinationViewController;
    vc.newsData = newsData;
    NSLog(@"%@",newsData);
}

After this i can have title of news with key "title" in my cell. So when i push on my cell i can see the second ViewController with my news with key "text" but with all keys (i have above 10 keys in JSON).

In the second ViewController with UITextView For parse news i wrote this code:

In h file:

@interface WebController : UIViewController{
    IBOutlet UIWebView *internetBrowser;
}
@property (nonatomic,strong) NSDictionary *newsData;
@property (nonatomic,weak) IBOutlet UITextView *textView;
@end

in m file:

@synthesize newsData = _newsData,textView = _textView;
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *allData;  
    for (NSString *key in _newsData.allKeys)
    {
        NSString *str = [NSString stringWithFormat:@"key = %@{ %@ }",key,[_newsData objectForKey:key]];
        allData = [NSString stringWithFormat:@"%@ \n %@ ",allData,str];
    }
    _textView.text = allData;
}

What i need: When i push on cell i must see only text with only one key not all only one. How its make? Help please. Thanks!

Upvotes: 1

Views: 441

Answers (1)

Mykola Denysyuk
Mykola Denysyuk

Reputation: 1985

I am confused that you serialize your data as dictionary while it's array

NSDictionary *playlist =[allDataDictionary objectForKey:@"data"];

so I'll write more then necessary code to avoid misunderstandings:

// ivar:
NSArray * _news;

// load and parse data:
// ...
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
_news =[allDataDictionary objectForKey:@"data"];

// configure cell
cell.textLabel.text = [_news[indexPath.row] valueForKey:@"title"];

// prepareForSegue:
// ...
NSDictionary *newsItem = [_news objectAtIndex:indexPath.row];
WebController *vc = (WebController*)segue.destinationViewController;
vc.newsData = newsItem;

// WebController's viewDidLoad:
// ...
_textView.text = [_newsData valueForKey:@"text"];

Upvotes: 2

Related Questions