最近在利用SBJSON開(kāi)發(fā)的過(guò)程中,發(fā)現(xiàn)SBJSON無(wú)法支持自定義的對(duì)象,為此考慮到了兩種實(shí)現(xiàn)方案。一種在SBJSON框架一層實(shí)現(xiàn)一個(gè)自定義對(duì)象的Category以支持proxyForJson的方法。另一種方案就是應(yīng)用層將自定義對(duì)象轉(zhuǎn)換成屬性名和屬性值的字典后再交由SBJSON處理。鑒于本次SBJSON由一個(gè)底層庫(kù)維護(hù),折中方案就是在應(yīng)用層進(jìn)行自定義對(duì)象的處理。經(jīng)過(guò)一番調(diào)查和搜索后,發(fā)現(xiàn)如下的實(shí)現(xiàn)方法:
為福安等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及福安網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、福安網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
- #import
- #import
- @interface NSObject (PropertyListing)
- // aps suffix to avoid namespace collsion
- // ...for Andrew Paul Sardone
- - (NSDictionary *)properties_aps;
- @end
- @implementation NSObject (PropertyListing)
- - (NSDictionary *)properties_aps {
- NSMutableDictionary *props = [NSMutableDictionary dictionary];
- unsigned int outCount, i;
- objc_property_t *properties = class_copyPropertyList([self class], &outCount);
- for (i = 0; i < outCount; i++) {
- objc_property_t property = properties[i];
- NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
- id propertyValue = [self valueForKey:(NSString *)propertyName];
- if (propertyValue) [props setObject:propertyValue forKey:propertyName];
- }
- free(properties);
- return props;
- }
- @end
利用一些JSON框架進(jìn)行自定義對(duì)象傳輸時(shí)處理如下:
- // The Person class has `firstName` and `lastName`
- // properties.
- // andrew is a Person instance with NSString values
- // of "Andrew" and "Sardone" for `firstName` and
- // `lastName` respectively.
- NSString *jsonString = [[andrew properties_aps]
- JSONRepresentation];
- // now `jsonString` looks like:
- // { "firstName": "Andrew", "lastName": "Sardone" }
代碼鏈接: http://forrst.com/posts/Getting_a_dictionary_of_an_NSObjects_property_n-h3T