2014-04-23 2 views
1

프로젝트에서 우리는 서비스에서 json으로 값을받습니다.JSON 직렬화 반환 null

대부분 내 질문에 여러 번 질문했지만 해결책을 찾지 못했습니다. 여기

코드 블록이다

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

    NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response ==> %@", responseData); 
    NSError *error = nil; 

    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error]; 

    NSString* userID = [jsonData objectForKey:@"user_ID"]; 
    NSLog(@"Success: %ld userID: %ld",(long)success, (long)userID); 

로그 :

응답 코드 : 200

응답 ==>

{ "용할 user_ID"4}

성공 : 0 사용자 ID : 0

json 개체를 문자열로 변환하려고하지만 jsonData의 콘텐츠를 인쇄 할 때 null이 반환됩니다. JSONSerializaton에 문제가있는 것 같습니다. 누구든지 해결책을 제안 할 수 있습니까? 다음 코드로

감사합니다, 미트

+1

'jsonData'는'nil'입니다. 맞으면 '오류'를 기록하십시오. – rmaddy

+0

jsonData가 nil이 아니라고 확신하지 못합니다. NSLog (@ "% @", jsonData);를 시도하십시오. – user3386109

+0

불행히도 NSLog (@ "JsonData : % @", jsonData); JsonData를 반환합니다 : (null) @rmaddy –

답변

0

그냥 테스트, 그것은 OK입니다. 오류를 기록하고 응답 데이터를 검사해야하며 잘못된 인코딩이 포함되어있을 수 있습니다.

const char *jsonStr = "{\"user_ID\":4}\n"; 
NSData *jsonData = [NSData dataWithBytes:jsonStr length:strlen(jsonStr)]; 
NSError *error = NULL; 
NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 
NSNumber *userIDObj = [jsonObj objectForKey:@"user_ID"]; 
NSInteger userID = [userIDObj integerValue]; 
NSLog(@"=========>User ID: %d", userID); 
+0

나를 위해 일했다. 감사. –