2011-05-08 3 views
0

JSON 문자열을 사용자 정의 복합 객체로 deserialize해야합니다.NSDictionary 객체를 사용자 정의 복합 객체로 변환

{"Menu": { 
"categoryList": { 
"Category": [ 
{"name": "Cat1"}, 
{"name": "Cat1"}, 
{"name": "Cat3"} 
] 
} 
}} 

가 어떻게 유형 분류 클래스의 3 개 종류의 객체를 포함하는 categoryList이있는 메뉴 개체를 초기화하기 위해이 문자열을 역 직렬화 할 수 있습니다 : 예를 들어

내가 JSON 문자열이 있다고 할 수 있습니다? 이 방법이 있습니까?

답변

-1

JSON 구문 분석기를 사용해보십시오.

http://code.google.com/p/json-framework/

그것은 당신의 문자열을 분석하고 데이터를 나타내는 NSObject의 (있는 NSArray 나 NSDictionary에을)를 돌려 줄 것입니다.

편집 : OP는 대신 NSDictionary에 /있는 NSArray의 사용자 지정 개체를 가져 원하는대로

글쎄, 그것으로 뭔가를 구현할 수있다하여 dificulty 정확한 데이터를 얻을 수 및 각을 설정한다고 가정 (다음 새로운 개체 속성)

code provided by @andrewsardone을 바탕으로

, 하나는 쉽게 어떤 솔루션을 구문 분석 JSON을 처리 한 후, 그에 따라 설정 한 속성을 가진 새로운 개체를 가져 KVO를 사용하여 기능을 구현할 수있는 프로젝트 더 나은

+(id) objectFromDictionary:(NSDictionary *)dict { 

    id entry = [[self alloc] init]; 

    Class aClass = [entry class]; 

    do { 

     unsigned int outCount, i; 
     objc_property_t *properties = class_copyPropertyList(aClass, &outCount); 
     for (i = 0; i < outCount; i++) { 
      objc_property_t property = properties[i]; 
      NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding] autorelease]; 
      id propertyValue = [dict objectForKey:propertyName]; 
      if (propertyValue && ![propertyValue isEqual:[NSNull null]]) { 
       [entry setValue:propertyValue forKey:propertyName]; 
      } 
     } 

     free(properties); 

     //added to take care of the class inheritance 
     aClass = [aClass superclass]; 

    } while (![[[aClass class] description] isEqualToString:[NSObject description]]); 

    return [entry autorelease]; 
} 
에 맞는
+1

nsarray 및 nsdictionary는 사용자 정의 객체가 아닙니다 –

+0

@rocity 그래서 마지막 편집 내용은 OP가 찾고있는 것으로 보이는 사용자 정의 객체 솔루션을 추가했습니다. –

0

이것은 좋은 (공용) 솔루션이 존재하지 않는 것으로 보이는 필요한 기능입니다.

관련 문제