2013-07-19 2 views
0

많은 개체에서 JSON 문자열을 만들려고합니다. 기본적으로 데이터베이스의 일부를 서버에 다시 보내서 마지막으로 연결 한 이후 업데이트 된 내용을 업데이트 할 수 있습니다. 개체 사전을 NSData 또는 JSON String으로 변환하여 전송할 수 있기를 기대했지만 NSJSONSerialization dataWithJSONObject를 호출 할 때 실패했습니다. 어떤 생각이 최선의 접근 방법은? 이러한 개체 각각을 개별적으로 수행해야합니까? 그렇다면 어떻게하면 커스텀 객체 배열을 처리 할 수 ​​있을까요?Objective C : Dictionary of NSArrays, NSDictionaries 및 사용자 지정 개체로 JSON 문자열을 만들려고합니다.

SchedModel *sched = [self retrieveSchedData]; //custom object 
NSArray *event = [self retrieveEvents]; //Array of custom objects 
NSDictionary *info = [self retrieveInfo]; //plain old NSDictionary 

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 

// Load all objects into a dictionary 
[dict setObject: sched forKey:@"sched"]; 
[dict setObject: event forKey:@"event"]; 
[dict setObject: info forKey:@"info"]; 

NSError * error = nil; 

//Now create the NSData for this object (THIS FAILS) 
NSData * jsonData = [NSJSONSerialization dataWithJSONObject: dict options:NSJSONReadingMutableContainers error:&error]; 
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; 

답변

0

사용자 지정 개체를 serialize 할 수 없습니다. 직렬화하기 전에 schedNSDictionary으로 변환해야합니다.

+0

sched를 사전으로 변환하는 일반적인 방법이 있거나 내 모든 사용자 정의 개체에서 toDictionary 메서드를 만들어야 할 필요가 있습니다. – DaveB

+0

그게 주요 방법이 될거야, 오직 당신이 어떤 속성/iVars가 직렬화되어야하는지 알기 때문이다. 그러나 Obj-C 런타임을 사용하여 모든 속성을 검사하고 인코딩 할 수 있습니다. –

+0

그런 일을하는 [Mantle] (https://github.com/github/Mantle)을 볼 수 있습니다. –