спросите, используя json в xcode4 - PullRequest
1 голос
/ 02 февраля 2012

Здравствуйте, я новичок в iPhone Dev я хочу, чтобы отобразить массив выбора с JSON для MySQL в Xcode4 у меня есть вывод JSON-код в PHP, как это:

{"data":[{"id":"16","nama":"yes","desk":"test2","gambar":""}]}

и мой кодовый модуль вот так:

list.m

- (void)viewDidLoad
{
    AIR = [[NSMutableArray alloc] init];

    NSURL *url = [NSURL URLWithString:@"http://192.168.0.169/demo/json/rifle.php"];

    NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
    NSLog(jsonreturn);

    NSData *jsonData =[jsonreturn dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error =nil;

    NSDictionary *dict =[[CJSONDeserializer deserializer]deserializeAsDictionary:jsonData error:&error];
    if (dict) {
        AIR = [[dict objectForKey:@"data"] retain];
    }
    NSLog(@"Array:%@",AIR);
}


#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 [AIR count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSDictionary *dict = [AIR objectAtIndex:indexPath.row];

    // deklarasi image ambil file gambar didalam field nama
    cell.textLabel.text = [dict objectForKey:@"nama"];

    // deklarasi image ambil file gambar didalam field desk
    cell.detailTextLabel.text = [dict objectForKey:@"desk"];

    // deklarasi image ambil file gambar didalam field gambar
    UIImage *cellImage =[UIImage imageNamed:[dict objectForKey:@"gambar"]];
    cell.imageView.image = cellImage;


    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    subway *mAIR = [[subway alloc] initWithNibName:@"subway" bundle:nil];
    [mAIR setTitle:@"AIRGUN DESC DETAIL"];
    [self.navigationController pushViewController:mAIR animated:YES];
    [mAIR release];
}

subway - другой ViewController с tableView iniNibName subway. Теперь мой вопрос, как я могу получить $ id (см. Код json) для массива select если в php нравится этот комментарий

SELECT * FROM data where id="$id"

, поэтому, если я выберу список NIB, они будут отображать вывод в метро NIB

может помочь мне, пожалуйста

спасибо до

Ответы [ 3 ]

0 голосов
/ 02 февраля 2012

Использовать JSONKit https://github.com/johnezang/JSONKit

Вам нужно всего 2 файла (JSONKit.h и JSONKit.m) - скопируйте его в свой проект. Затем вам нужно импортировать его в свой файл .m:

#import "JSONKit.h"

Загрузите ваши данные в NSString * jsonString, как вы хотите, и затем используйте:

NSArray *jsonArray = [jsonString objectFromJSONString];

В этом массиве вы получите свой ответ, а теперь используйте NSDictionary или NSArray для получения переменных (зависит от данныхв ответе json) - NSDictionary является ключом: значением, а NSArray является просто массивом объектов.

Таким образом, чтобы получить ID = 16 из ответа json, вам нужно что-то вроде:

NSLog(@"My ID is %@", [[jsonArray objectAtIndex:0] objectForKey:@"id"]);

Вы можете в любое время проверить содержимое NSDictionary или NSArray, например NSLog (@ "% @", jsonArray);

Или, если раздел "data" является словарем, используйте [[jsonDictionary objectForKey: @ "data"] objectForKey: @"id"] Поскольку у вас есть словарь и внутри него, это еще один структурированный ответ словаря.

0 голосов
/ 23 октября 2013

Вот самый простой метод анализа json, надежда поможет вам

ViewController.h

 @interface ViewController : UIViewController <NSURLConnectionDelegate>
 {
    NSArray *ids;
    NSArray *nama;
    NSArray *desk;
    NSArray *gambar;

   //=======Json Variable
   NSMutableData *webdata;
   NSURLConnection *conn;
  //======
 }

ViewController.m

- (void)viewDidLoad
{
     [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

   NSString *urlstring=[NSString stringWithFormat:@"http://192.168.0.169/demo/json/rifle.php"];
  NSURL *url=[NSURL URLWithString:urlstring];
  NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url];
  conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn) {
    webdata = [[NSMutableData alloc] init];
  }

}

#pragma NSUrl Connection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
     [webdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
     [webdata appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
      NSString *str=[[NSString alloc]initWithBytes:[webdata mutableBytes] length:[webdata length] encoding:NSUTF8StringEncoding];
     NSLog(@"Data Length %d",[webdata length]);
     NSMutableDictionary *result = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

    ids = [[result valueForKey:@"data"] valueForKey:@"id"];
    nama = [[result valueForKey:@"data"] valueForKey:@"nama"];
    desk = [[result valueForKey:@"data"] valueForKey:@"desk"];
    gambar = [[result valueForKey:@"data"] valueForKey:@"gambar"];
}
0 голосов
/ 02 февраля 2012

Я делаю то же самое и использую библиотеки SBJSON:

https://github.com/stig/json-framework/

  • DownloadedData - это JSON, который вы получаете от веб-службы
  • parsedData - это NSDicitonary с анализом JSON

    NSString *responseString = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];    
    
    SBJSON *parser = [SBJSON new];
    
    NSDictionary *parsedData = (NSDictionary *)[parser objectWithString:responseString error: nil];
    [responseString release];
    
    
    [parser release];
    

Вы можете найти учебник здесь: http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...