2014-04-16 2 views
1

저는 iOS의 초보자이며 약간의 문제가 있습니다. 인덱스 i와 키 x에 대해 JSONObject에서 데이터를 가져 오는 방법을 알지 못합니다.(iOS) 배열에있는 json의 데이터를 추가하십시오.

그냥 아래

-(NSMutableArray*)getAll{ 
    NSMutableArray* liste; 

    dispatch_queue_t downloadQueue = dispatch_queue_create("Get All Offers", NULL); 

    dispatch_async(downloadQueue, ^{ 
     NSData *result = [self executePostCall]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 

      id strResult=nil; 
      NSError* error; 
      strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:&error]; 
      for(int cpt=0; cpt>[strResult count];cpt++) 
      { 
       [liste addObject:[NSMutableArray new]]; 

       // ERREUR ICI !!!!!!!!! 

       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"titre"]]]; 
       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"srcImage"]]]; 
       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"date"]]]; 
       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"prix"]]]; 
       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"ville"]]]; 
       [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"categorie"]]]; 
      } 


     }); 
    }); 
    NSLog(@"liste: %@",liste); 
    return liste; 
} 

내가 라인 CPT에서 키 (예 : "역가")으로 객체를 얻기 위해 시도 내 코드가있다. 도와 줄수있으세요 ?

나는 문제가 내가 [[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[strResult objectAtIndex:cpt] objectForKey:@"titre"]]];을하고있을 때이지만 나는 그것을 해결하는 방법을 모른다라고 생각한다.

[self executePostCall]은 잘 작동하는 또 다른 기능입니다. JSON에 따라 당신의 도움이

+0

JSON 응답과 비슷한 모양을 보여줄 수 있습니까? – Larme

+0

@Larme 코드가 바로 아래에 있습니다. 도움을 주셔서 감사합니다. – ben77650

답변

2

에 대한

덕분에, 객체가 [NSJSONSerialization JSONObjectWithData]에서 반환하는 것은 어느 쪽 NSArray 또는 NSDictionary. objectAtIndex이 작동하지 않으면 NSDictionary을 상대 할 가능성이 있습니다.

if([strResult isKindOfClass:NSArray.class]) { 
    // Do something that deals with an array 

} else if([strResult isKindOfClass:NSDictionary.class]) { 
    // Do something that deals with a dictionary 

} 
1

감사 답변이 & @Bob Vork을 @Larme을 위해 :

이동하는 가장 안전한 방법은 코드에서 어느 하나 확인하는 것입니다. 그냥 executePostCall 방법 아래

:

- (NSData *)executePostCall { 
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", @"http://www.mysite.com/listAllAnn.php"]]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

NSString *requestFields = @""; 
requestFields = [requestFields stringByAppendingFormat:@"table=%@&", table]; 
requestFields = [requestFields stringByAppendingFormat:@"limit=%d&", limit]; 
requestFields = [requestFields stringByAppendingFormat:@"offset=%d", offset]; 

requestFields = [requestFields stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSData *requestData = [requestFields dataUsingEncoding:NSUTF8StringEncoding]; 
request.HTTPBody = requestData; 
request.HTTPMethod = @"POST"; 


NSHTTPURLResponse *response = nil; 
NSError *error = nil; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
if (error == nil && response.statusCode == 200) { 
} else { 
    //Error handling 
} 
return responseData; 

} 

는 그리고 이것은 "listAllAnn.php"나는 MySQL 데이터베이스에서 정보를 얻기 위해 사용하는 웹 서비스입니다. 내 직장 동료가 Android 응용 프로그램에 사용하기 때문에 나는 괜찮다고 확신합니다.

strResult: 1496 

그것은 내가 같이있어 :

<?php 

$response = array(); 

$db = new DB_CONNECT(); 

mysql_query('SET CHARACTER SET utf8'); 


$table=$_POST["table"]; 
$limit=$_POST["limit"]; 
$offset=$_POST["offset"]; 

$result = mysql_query("SELECT * FROM $table WHERE etat = 2 order by date DESC LIMIT $limit OFFSET $offset") or die(mysql_error()); 

if (mysql_num_rows($result) > 0) { 


while ($row = mysql_fetch_array($result)) { 
    $ann = array(); 
    $ann["id"] = $row["id_ann"]; 
    $ann["cat"] = $row["id_cat"]; 


    $response[]= $ann; 

} 

echo json_encode($response); 
} else { 
$response["success"] = 0; 
$response["message"] = "No products found"; 

echo json_encode($response); 
} 
?> 

strResult의 오브제 내가 NSLog

strResult:{ 
cat = 46; 
id = 1496; 
} 

을 할 때 내가

NSLog(@"strResult: %@",[[strResult objectAtIndex:0] objectForKey:@"id"]); 

작업을 수행 할 때 내가 가진 것을 나에게 전송 정보를 얻으려면 아래 코드를 사용해야하지만 kn은 아닙니다. 왜냐하면 나는 정보를 얻기 위해 사용하고있는 것들을 제외하고 webservice에 어떤 키도 가지고 있지 않기 때문에 첫 번째 "objectForKey"에서 어떤 키를 사용해야하는지.

[[liste objectAtIndex:cpt] addObject:[[NSString alloc] initWithFormat:@"%@",[[[strResult objectForKey:@""]objectAtIndex:cpt] objectForKey:@"titre"]]]; 
+0

답변을위한 섹션에 추가하지 말고 추가 질문으로 원래 질문을 편집하십시오. – Abizern

+0

@Abizem, 오케이 미안해, 내가 새로운데, 사이트 작동 방식을 발견해. – ben77650

1

liste에게

있는 NSMutableArray liste * = [있는 NSMutableArray의 ALLOC] INIT]를 initializaing 시도; 또한 [NSString stringWithFormat : @ "% @", xyz];를 직접 사용할 수 있습니다.

희망이 있습니다. 출력을 알려주세요.