0

SBJsonParser를 사용할 때 일부 JSON을 구문 분석 할 때 현재 이상한 문제가 발생합니다.JSON 구문 분석 - SBJsonParser 관련 문제

이제 구문 분석하는 JSON은 다음과 같습니다.

[ 
    { 
     "Company":{ 
     "id":"1", 
     "company_name":null 
     }, 
     "relations":{ 
     "store":[ 
      { 
       "id":"1", 
       "restaurant_name":"Dubai", 
       "brief_description":null 
      }, 
      { 
       "id":"2", 
       "restaurant_name":"Test2", 
       "brief_description":null 
      } 
     ] 
     } 
    } 
] 

나는 쉽게있는 NSDictionary를 작성하고 회사노드에 대한 올바른 정보를 입력 할 수 있습니다 (?).

하지만 관계 노드가 발생할 때 내 문제가 발생합니다.

NSDictionary *relations = [object valueForKey:@"relations"]; 
NSArray *multipleStores = [relations valueForKey:@"store"]; 
NSLog(@"relations: %@", relations); 

for (NSDictionary *singleStore in multipleStores){ 

     NSLog(@"Single Store: %@", singleStore); 

     [company grabStoreInformation:singleStore]; 

} 

위의 내용은 NSLog가 반환 한 것입니다.

relations: (
    { 
    store =   (
        { 
      "brief_description" = "<null>"; 
      id = 1; 
      "restaurant_name" = Dubai; 
     }, 
        { 
      "brief_description" = "<null>"; 
      id = 2; 
      "restaurant_name" = Test2; 
     } 
    ); 
} 
) 

NSLog에서 발생한 상황이 아니라면 괜찮습니다. singleStore가 개별 저장소 노드를 실제로 얻지는 않지만 저장소 노드를 함께 추가하는 것으로 보입니다.

Single Store: (
    { 
    "brief_description" = "<null>"; 
    id = 1; 
    "restaurant_name" = Dubai; 
    }, 
    { 
    "brief_description" = "<null>"; 
    id = 2; 
    "restaurant_name" = Test2; 
    } 
) 

문제는 각 저장소 노드를 NSMutableArray에 추가해야한다는 것입니다. 따라서 NSDictionary는 NSMutableArray에 추가 된 다음 다른 곳에서 액세스 할 수 있습니다 (UITableView 데이터 소스의 경우).

저장소 노드를 분리하는 데 많은 도움을 주실 수 있습니다. 구문 분석에 대한 전체 코드, 요청으로

편집 :

 SBJsonParser *parser = [[SBJsonParser alloc] init]; 

     // parse the JSON string into an object - assuming [response asString] is a NSString of JSON data 
     NSDictionary *object = [parser objectWithString:[response asString] error:nil]; 

     [parser release]; 

     NSDictionary *companyDetails = [object valueForKey:@"Company"]; 

     MACompany *company = [MACompany sharedMACompany]; 
     [company initWithDetails:companyDetails]; 

     NSDictionary *relations = [object valueForKey:@"relations"]; 
     NSArray *multipleStores = [relations valueForKey:@"store"]; 

     NSLog(@"relations: %@", relations); 

     for (NSDictionary *singleStore in multipleStores){ 

      NSLog(@"Single Store: %@", singleStore); 

      [company grabStoreInformation:singleStore]; 

     } 

당신은 내가 JSON의 요소를 복사하는 싱글 톤 클래스에 의존 볼 수 있듯이. 이것은 내가 생각하기에, 단일 상점 사전을 분할하는 방법을 연구 할 때 달성하고자하는 것과 관련이 있다고 생각합니다.

+0

주제를 벗어나지 만 OS5를 타겟팅하는 경우 내장 된 JSON 파서를 사용할 수 있습니다 – Devraj

+0

우리는 iOS4도 지원합니다. 내 의견으로는 두 프로세스 모두 동일한 프로세스를 사용할 수 있습니다. –

+0

@SebastienPeek 충분히 공정하게 :) – Devraj

답변

1

먼저, 최상위 요소는 개체가 아니라 배열입니다. 따라서 :

NSArray *object = [parser objectWithString:[response asString] error:nil]; 

을 내가 변수 이름으로 companies 대신 object을 사용하십시오 :

NSDictionary *object = [parser objectWithString:[response asString] error:nil]; 

이 있어야한다.

둘째, -valueForKey:을 사용할 때는주의해야합니다. 배열로 보내면 다른 배열을 반환하며 키 인수에 해당하는 값을 포함합니다. 키 - 값 코딩에 익숙하지 않은 경우 NSDictionary의 표준 메소드를 사용하여 주어진 키와 연결된 객체를 반환하십시오 (-objectForKey:).

-valueForKey: 대신 -objectForKey:을 사용했다면 프로그램을 실행할 때이 구조 오류가 발생했을 것입니다.다음과 같이 염두에 두 점

, 당신은 당신의 JSON 데이터를 탐색 할 수 있습니다 :

NSArray *companies = [parser objectWithString:[response asString] error:nil]; 
for (NSDictionary *company in companies) { 
    NSDictionary *companyDetails = [company objectForKey:@"Company"]; 
    NSDictionary *relations = [company objectForKey:@"relations"]; 
    NSArray *stores = [relations objectForKey:@"store"]; 

    for (NSDictionary *store in stores) { 
     NSString *restaurantName = [store objectForKey:@"restaurant_name"]; 
     … 
    } 

을 내가 스택 오버플이 다른 질문을 읽어 보시기 바랍니다 : Difference valueforKey objectForKeyKey-Value Coding Programming Guide-valueForKey:를 사용하기 전에.

+0

완벽하게 작동합니다. 내 유일한 문제는 NSMutableArray에 NSDictionary * 저장소를 추가하여 나중에 꺼낼 수 있다는 것입니다. [NSMutableArray addObject : store]를 수행 할 수 있습니까? –

+1

@Sebastien 확실합니다. 또 다른 옵션은'stores' 배열의 가변 복사본을 만드는 것입니다. 'NSMutableArray * storesArray = [stores mutableCopy]'. –

+0

감사합니다. 정말로 도움이되었습니다! –