2014-12-04 3 views
0

NSDictionary를 JSON으로 변환하는 방법은 무엇입니까?NSDictionary를 JSON으로 변환

json을 사용하여 서버에 사전을 게시했습니다. 그리고 GET 방식을 사용하여 서버로부터 데이터를 수신 할 때.

_secretanswer.text=[[NSString alloc]initWithFormat:@"%@",[customfield objectForKey:@"secanswer"]]; 

과 같은 일반 키 호출 메소드를 사용하여 데이터를 액세스 할 수 없으므로 서버는 NCFString을 결과로 반환합니다.

NSDictionary를 JSON 형식으로 변환하고 게시하는 방법은 무엇입니까?

+1

JSON 또는 제이슨? – Dev

+2

누가 _JASON입니까? _ – holex

답변

0
NSError * error; 
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&error]; 

NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]  
+0

OP는 명시 적으로 NSString이 아닌 JSON 데이터에서 NSDictionary를 찾고 있음이 분명합니다. – geraldWilliam

0

당신이 찾고있는 것이 NSJSONSerialization이라고 믿습니다.

이 답변은 NSURLConnection의 블록 기반 API를 사용하여 GET을 실행한다고 가정합니다.

하지만 dataWithContentsOfURL :을 사용하는 경우에도 마찬가지입니다. NSJSONSerialization의 + jsonObjectWithData : options : error : 메소드에 데이터를 입력하고, 사전을 다시 얻었는지 확인한 후 계속 진행하십시오.

EDIT : NSDictionary의 HTTP 요청에 대한 JSON 게시 본문을 만들려면 NSJSONSerialization을 사용하십시오.

NSError *error = nil; 
NSData *data = [NSJSONSerialization dataWithJSONObject:someDictionary options:NSJSONWritingPrettyPrinted error:&error]; 
if (data) { 
    // You got your data. 
    NSLog(@"my data: %@", data); 
    [someURLRequest setHTTPBody:data]; 
} else if (error) { 
    NSLog(@"error: %@", [error localizedDescription]); 
} 
+1

오류 처리를 포함하지 않기 때문에 Downvoted. –

+0

@HotLicks 감사합니다. 답변이 업데이트되었습니다. – geraldWilliam

+0

추가 된 오류 처리에서 자주 실수했습니다. https://www.bignerdranch.com/blog/an-nserror-error/ https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html#//apple_ref를 참조하십시오./doc/uid/TP40011210-CH9-SW5 –