NSJON Serialization 오류 - JSON 쓰기(메뉴)에 잘못된 유형이 있습니다.
나는 매우 유사한 속성을 가진 3개의 엔티티를 가진 핵심 데이터를 사용하는 앱을 가지고 있다.관계는 다음과 같습니다.
지점 ->> 메뉴 -> 카테고리 -> Food Item
각 엔티티에는 관련된 클래스가 있습니다.예

sqlite 데이터베이스에 데이터의 JSON 표현을 생성하려고 합니다.
//gets a single menu record which has some categories and each of these have some food items
id obj = [NSArray arrayWithObject:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
하지만 JSON 대신 SIGABRT 오류가 발생합니다.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Menu)'
수정 방법 또는 엔티티 클래스(브런치, 메뉴 등)의 JSON 시리얼라이제이션에 호환성을 갖게 하는 방법이 있습니까?
이는 JSON에서 "메뉴" 클래스를 직렬화할 수 없기 때문입니다.기본적으로 언어에서는 오브젝트가 JSON에서 어떻게 표현되어야 하는지 알 수 없습니다(포함하는 필드, 다른 오브젝트에 대한 참조를 표시하는 방법 등).
NSJONSerialization 클래스 레퍼런스에서
JSON으로 변환할 수 있는 개체는 다음 속성을 가져야 합니다.
- 최상위 개체는 NSArray 또는 NSDictionary입니다.
- 모든 오브젝트는 NSString, NSNumber, NSAray, NSDictionary 또는 NSNull 인스턴스입니다.
- 모든 사전 키는 NSString 인스턴스입니다.
- 숫자는 NaN이나 무한대가 아닙니다.
이것은 그 언어가 사전을 직렬화하는 방법을 알고 있다는 것을 의미합니다.따라서 메뉴에서 JSON 표현을 얻는 간단한 방법은 메뉴 인스턴스의 사전 표현을 제공하는 것입니다. 그러면 JSON으로 일련화할 수 있습니다.
- (NSDictionary *)dictionaryFromMenu:(Menu)menu {
[NSDictionary dictionaryWithObjectsAndKeys:[menu.dateUpdated description],@"dateUpdated",
menu.categoryId, @"categoryId",
//... add all the Menu properties you want to include here
nil];
}
다음과 같이 사용할 수 있습니다.
NSDictionary *menuDictionary = [self dictionaryFromMenu:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuDictionary options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
클래스 메서드가 있습니다.isValidJSONObject에NSJSONSerialization개체를 직렬화할 수 있는지 여부를 알려줍니다.줄리앙이 지적한 것처럼 당신은 아마도 당신의 오브젝트를 변환해야 할 것입니다.NSDictionary.NSManagedModel그럼 엔티티의 모든 Atribute를 취득하기 위한 편리한 방법을 몇 가지 나타냅니다.따라서 다음 카테고리를 생성할 수 있습니다.NSManagedObject변환하는 방법을 가지고 있다.NSDictionary. 이렇게 하면 critude를 쓸 필요가 없습니다.toDictionary사전으로 변환할 각 엔티티의 메서드를 지정합니다.
@implementation NSManagedObject (JSON)
- (NSDictionary *)toDictionary
{
NSArray *attributes = [[self.entity attributesByName] allKeys];
NSDictionary *dict = [self dictionaryWithValuesForKeys:attributes];
return dict;
}
NSJON Serialization 클래스의 + isValidJSONObject: 메서드를 사용할 수 있습니다.유효하지 않은 경우 - initWithData:encoding: method of NSString을 사용할 수 있습니다.
- (NSString *)prettyPrintedJson:(id)jsonObject
{
NSData *jsonData;
if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
NSError *error;
jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject
options:NSJSONWritingPrettyPrinted
error:&error];
if (error) {
return nil;
}
} else {
jsonData = jsonObject;
}
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
키를 @{value :@"key"} 값으로 전환했습니다. @{@"key":value}이어야 합니다.
언급URL : https://stackoverflow.com/questions/9893217/error-with-nsjsonserialization-invalid-type-in-json-write-menu
'programing' 카테고리의 다른 글
| 클래스 컴포넌트에서 React.useRef()를 사용하는 방법 (0) | 2023.03.20 |
|---|---|
| 스프링 캐시 Java에서 여러 캐시 매니저 구성을 사용하는 방법 (0) | 2023.03.20 |
| ui-bootstrap-tpls.min.js와 ui-bootstrap.min.js의 차이점은 무엇입니까? (0) | 2023.03.20 |
| angularjs를 사용하여 저장되지 않은 데이터 감지 (0) | 2023.03.15 |
| 그물 잡는 법:ERR_CONNECTION_REFUSED (0) | 2023.03.15 |