2011-08-12 3 views
2

sbjsonparser를 사용하여 json 문자열을 구문 분석하려고합니다. 임 nsdictionary로 변환하는 데 문제가 있습니다. 나는 다른 클래스에서 sbjsonparser를 사용했고 모두 잘 작동했습니다. 내 코드를 참조하십시오.json string을 nsdictionary로 구문 분석 할 수 없습니다.

2011-08-12 13:56:55.098 EasyQuiz[5446:13603] [{ 
"q": "Question Testing", 
"score": 1, 
"c3": "Choice C", 
"c2": "Choice B", 
"c1": "Choice A", 
"rev": 1, 
"id": 1, 
"c4": "Choice D" 
}] 
2011-08-12 13:56:55.686 EasyQuiz[5446:13603] (null) 
2011-08-12 13:56:56.296 EasyQuiz[5446:13603] -JSONValue failed. Error is: Illegal start 
of token [] 
2011-08-12 13:56:56.297 EasyQuiz[5446:13603] (null) 

내가 http://jsonformatter.curiousconcept.com/에서 문자열을 확인하고 유효한 것으로 나타납니다

-(void)parseJsonString 
{ 
    NSLog(@"%@",jsonString); 
    SBJsonParser *parser = [[SBJsonParser alloc] init]; 
    NSDictionary *dict; 
    dict = [parser objectWithString:jsonString error:nil]; 
    NSLog(@"%@",dict); 


    NSDictionary *dict2; 
    dict2 = [jsonString JSONValue]; 
    NSLog(@"%@",dict2); 

    [parser release]; 

}

여기에 내 콘솔 출력입니다. 이 문제의 원인은 무엇이라고 생각하십니까? 감사!

dict = [파서 objectWithString : jsonString 오류 : nil];에서 오류를 인쇄했습니다. 그리고는 말한다 :

Error Domain=org.brautaset.SBJsonParser.ErrorDomain Code=0 "Illegal start of token []" 
    UserInfo=0x62eb920 {NSLocalizedDescription=Illegal start of token []} 

편집 나는이

NSString *thisJsonString = @"[{\"q\": \"Question Testing\",\"score\": 1, \"c3\": \"Choice C\", \"c2\": \"Choice B\", \"c1\": \"Choice A\", \"rev\": 1, \"id\": 1, \"c4\": \"Choice D\"}]"; 

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

NSDictionary *dict; 

dict = [parser objectWithString:thisJsonString error:nil]; 
NSLog(@"dict %@",dict); 

[parser release]; 

처럼 jsonstring을 하드 코딩 시도하고 내가 콘솔에서 원하는 걸 얻었 :

dict (
    { 
    c1 = "Choice A"; 
    c2 = "Choice B"; 
    c3 = "Choice C"; 
    c4 = "Choice D"; 
    id = 1; 
    q = "Question Testing"; 
    rev = 1; 
    score = 1; 
} 
) 

편집을 내가 데이터를 어디에서 얻고 싶은지 알고 싶을 때. asihttprequest를 사용하여 웹 사이트에서 zip 파일을 다운로드하고이 파일을 objective-zip을 사용하여 추출하면 압축이 풀린 파일이 이와 같이 읽혀집니다.

NSString *filePath = [[self applicationDocumentsDirectory] 
stringByAppendingPathComponent:@"json.zip"]; 

    //Opening zip file for reading... 
    progressLabel.text = @"Reading file..."; 
    ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:filePath mode:ZipFileModeUnzip]; 

    //Opening first file... 
    progressLabel.text = @"Opening file..."; 
    [unzipFile goToFirstFileInZip]; 
    ZipReadStream *read1= [unzipFile readCurrentFileInZip]; 

    //Reading from first file's stream... 
    NSMutableData *data1= [[[NSMutableData alloc] initWithLength:1000000] autorelease];//100MB 
    int bytesRead1= [read1 readDataWithBuffer:data1]; 
    NSLog(@"bytes: %d",bytesRead1); 
    if (bytesRead1 > 0) { 
     progressLabel.text = @"File is good!"; 
     jsonString = [[[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding] autorelease]; 
//.... more codes follow, but this is how I get jsonString 
+1

에 넣어하지만 그 배열 – Robin

+0

임하지 내가 바로 당신을 확실히 이해 사전이 아니라 임 이 코드를 사용하여 json 문자열을이 코드를 사용하여 nsdictionary로 변환합니다. 이 코드 조각은 다른 모든 클래스에서 잘 작동합니다. 이 피드는 저에게 오류를줍니다. SBJsonParser * parser = [[SBJsonParser alloc] init]; NSDictionary * dict; dict = [파서 objectWithString : jsonString 오류 : nil]; NSLog (@ "% @", dict); – Diffy

+0

문자열이 배열이면 강제로 사전으로 변환 할 수 없습니다. [JSON 표준] (http://www.json.org/) 봐 - JSON에서 "개체"NSDictionary 있지만 "배열"NSArray/ –

답변

-1

objectWithString : 오류 : 반환 형식을 ID을 데, 다음과 같이 코드를 수정하여 알려 주시기 바랍니다.

NSString *str = [NSString stringWithFormat:@"%@", [parser objectWithString:jsonString error:nil]]; 
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:str,@"response", nil]; 
    NSLog(@"%@",[dict description]); 
+0

이 예외가 : 예외가 발생했습니다 : NSException - [< __NSDictionary0 0x69d8750> setValue : forUndefinedKey :] :이 클래스는 키 응답에 대해 키 값 코딩을 준수하지 않습니다. – Diffy

+0

변경 가능한 사전이 아닙니다 ... – Robin

+0

내가 편집 한대로 주어진 코드를 확인하십시오. –

0

json은 하나의 개체 배열이므로 NSDictionary로 직접 구문 분석 할 수 없습니다. 첫째로있는 NSArray로 분석 한 후 첫 번째 개체를 가지고 내가 뭘 잘못 것입니다 확실하지 오전 NSDictionary와

-(void)parseJsonString 
{ 

    NSArray *jsonArray = (*NSArray)[jsonString JSONValue]; 

    NSDictionary *jsonDict = [jsonArray objectAtIndex:0]; 

    NSString *q = [jsonDict objectForKey:@"q"]; 
    ... 

} 
+0

이 오류가 발생합니다. -JSONValue가 실패했습니다. 오류 : 잘못된 토큰 시작 [] 및 문자열을 nslog 때이 얻을. (null) – Diffy

+0

동일한 오류가 발생합니다. NSString은 -JSONValue 메시지를 수신하지 않습니다. – meddlingwithfire

+0

그것을 알아 냈습니다. -JSONValue 실패 메시지가 나타나면 NSString + SBJSON.h 범주를 사용하고 있지 않은 것입니다. 원래의 질문 저자는 SBJSON 프로젝트를 사용하고 있다고 명시합니다. – meddlingwithfire