2012-08-17 2 views
1

서버에서 데이터를 성공적으로 가져 왔습니다. 그것을 얻은 후에 나는 파싱 할 함수에 데이터를 보낸다.NSJSONSerialization 구문 분석 오류가 사전이나 배열이 아닙니다.

- (void)readIn:(NSMutableData *)s { 
    NSLog(@"Reading in the following:"); 
    NSString * prints = [[NSString alloc] initWithData:s encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", prints); 

    NSError *error = nil; 
    NSData *jsonData = [[NSData alloc] initWithData:s]; 

    if (jsonData) { 

     id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 

     if ([jsonObjects isKindOfClass: [NSArray class]]) 
      NSLog(@"yes we got an Array"); 
     else if ([jsonObjects isKindOfClass: [NSDictionary class]]) 
      NSLog(@"yes we got an dictionary"); 
     else 
       NSLog(@"neither array nor dictionary!"); 



     if (error) { 
      NSLog(@"error is %@", [error localizedDescription]); 
      return; 
     } 

     NSArray *keys = [jsonObjects allKeys]; 
     for (NSString *key in keys) { 
      NSLog(@"%@ is %@",key, [jsonObjects objectForKey:key]); 
     } 

    } else { 

     // Handle Error 
    } 
    } 

이제 콘솔 내 인쇄 : 그것은 나에게 법적 JSON 개체를 보인다

2012-08-17 13:59:57.667 TaraftarlikOyunu[1157:c07] Reading in the following: 
2012-08-17 13:59:57.667 TaraftarlikOyunu[1157:c07] {"uID":"5878341","tm":"fb","hh":122,"pt":75,"coin":500,"ll":1,"qlevel":1,"coect":true,"potWeekly":{"pts":75,"intval":604800000},"acent":{"chamunt":0},"mes":[]} 
2012-08-17 13:59:57.668 TaraftarlikOyunu[1157:c07] neither array nor dictionary! 
2012-08-17 13:59:57.670 TaraftarlikOyunu[1157:c07] error is The operation couldn’t be completed. (Cocoa error 3840.) 

. 내가 뭘 잘못하고 있니?

nsstream을 사용하여 서버에서 데이터를 가져 오는 중입니다.

case NSStreamEventHasBytesAvailable: { 
      if(stream == inputStream) { 
       NSLog(@"inputStream is ready."); 

       uint8_t buf[1024]; 
       unsigned int len = 0; 

       len = [inputStream read:buf maxLength:1024]; 
      NSLog(@"length %i", len); 
       if(len > 0) { 

        NSMutableData* data=[[NSMutableData alloc] initWithLength:0]; 
        [data appendBytes: (const void *)buf length:len]; 
        [self readIn:data]; 

       } 
      } 
      break; 
     } 

답변

0

문제는 json 문자열이 끝날 때 null 종단이오고, NSDictionary 또는 NSArray로 변환 할 수 없도록 deserialize하려고 할 때입니다. 코드를 약간 수정하면 모든 것이 완벽 해집니다. 실제 코드는 다른 하나에서 해당

case NSStreamEventHasBytesAvailable: { 
     if(stream == inputStream) { 

      NSLog(@"inputStream is ready."); 

      uint8_t buf[1024]; 
      unsigned int len = 0; 

      len = [inputStream read:buf maxLength:1024]; 
      NSLog(@"length %i", len); 
      if(len > 0) { 

       datum =[[NSMutableData alloc] initWithLength:0]; 

       [datum appendBytes: (const void *)buf length:len-1]; 




       NSDictionary * jsondict = [NSJSONSerialization JSONObjectWithData:datum options:NSUTF8StringEncoding error:nil]; 

       NSLog(@"is valid json object %d",[NSJSONSerialization isValidJSONObject:jsondict]); 


       [self readIn:datum]; 
       } 
      } 
      else { 
       NSLog(@"no buffer!"); 
      } 
      break; 
      } 


    default: { 
     NSLog(@"Stream is sending an Event: %i", event); 

     break; 
    } 
} 

유일한 차이점처럼 내가 마지막 바이트를 던졌다하고 유효한 JSON 사전이되었다입니다해야합니다. 내 질문에 관심이있는 사람들에게 감사드립니다.

0

배열이어야하는 jsonObjects 설정을 명시 적으로 시도해보십시오 : 여기에 데이터를 얻을하려면 코드입니다

NSError *myError = nil; 

NSArray *jsonObjects= [NSJSONSerialization JSONObjectWithData:responseData ptions:NSJSONReadingMutableLeaves error:&myError]; 


for (NSDictionary * dict in jsonObjects) { 
    NSLog(@"Some data %@", [dict objectForKey:@"field"]); 
    //replace this to access a valid field 
    } 
+0

결과가 동일합니다. 아무것도 바뀌지 않았습니다 – meth

+0

아마 inbetween 단계로 jsonData를 사용하지 않으시겠습니까? id jsonObjects = [NSJSONSerialization JSONObjectWithData : s .... –

0

실패하는 이유는 원본 데이터가 아마 '\'문자를 가지고 있다는 것입니다 ""문자를 인용하고 있습니다. "Cocoa error 3840"을 검색했다면 힌트를 얻었을 것입니다. 내가 한 것은 한 번에 한 문자 씩 원본 데이터를 인쇄하는 것입니다 UTF의 경우) 확인하고이를 확인하십시오.

char * ptr = [s bytes]; f 또는 (int i = 0; i < [길이]; ++ i) NSLog (@ "% c", * ptr ++);

+0

반환 된 것은 객체가 아닌 nil이었습니다. 이것이 오류가 유효한 이유입니다. –

+0

예 처음에는 공백이 생기고 데이터 끝에는 '\ 0'이옵니다. – meth

+0

NSString은 문자열의 양쪽 끝에있는 공백을 "다듬을"수있는 편리한 방법을 가지고 있습니다. 분명히 그것을 사용할 수 있습니다. 널 (null). 자 열을 지울 수도 있습니다. 그러나 문제가 더 심각 할 것이므로 먼저 JSON을 얻는 방법을 정확하게 조사해야합니다. 행운을 빕니다! –

0

JSON은 JSON 문서에서 탭, 용지 공급, 캐리지 리턴 및 줄 바꿈 이외의 모든 제어 문자를 수락하지 않으므로 코드가 완벽하게 작동하고 읽지 않음으로써 수행해야하는 작업을 정확히 수행합니다. 아무것도.

그렇다면이 문자는 어디서 오는 것입니까? 데이터를 읽는 코드가 잘못되었거나 서버가 잘못되었습니다. 서버에 문제가있는 것처럼 보입니다. 마지막 문자를 버리면 "수정"됩니다. 서버가 고정되면 닫는 중괄호를 버립니다. 나는 서버에 대한 책임이있는 사람에게 연락하여 문제를 해결할 것입니다.