IOS 反射获取属性,序列化成JSON

继上篇序列化成xml,这篇介绍如何序列化成JSON对象。

只是稍有改动

ConvertObjToJSON.h

//
//  ConvertObjToJSON.h
// 
//
//  Created by Elliott on 13-3-5.
//  Copyright (c) 2013年 Elliott. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ConvertObjToJSON : NSObject

+(NSString *)Convert:(id)obj;

@end

ConvertObjToJSON.m

//
//  ConvertObjToJSON.m
//  
//
//  Created by Elliott on 13-3-5.
//  Copyright (c) 2013年 Elliott. All rights reserved.
//
#import <objc/runtime.h>
#import "ConvertObjToJSON.h"

@implementation ConvertObjToJSON

+(NSString *)Convert:(id)obj
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([obj class], &outCount);
    NSString *xml=@"{";
    for(i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *key=[[NSString alloc]initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        id value=[obj valueForKey:key];
        
        if (value!=nil) {
            //IF NOT NSSTRING,LOOP!!!!!!
            if (![value isKindOfClass:[NSString class]]) {
                xml=[xml stringByAppendingFormat:@"%@:%@,",key,[ConvertObjToJSON Convert:[obj valueForKey:key]]];
            }
            else
            {
                xml=[xml stringByAppendingFormat:@"%@:'%@',",key,value];
            }
        }
        else
        {
            xml=[xml stringByAppendingFormat:@"%@:'%@',",key,@""];
        }
    }
    xml=[xml substringToIndex:xml.length-1];
    xml=[xml stringByAppendingString:@"}"];
    
    //NSLog(@"结果:%@",xml);
    
    free(properties);
    
    return xml;
}
@end

调用方式和上一篇xml的一样。

目前只支持NSSTRING和自定义类。

 

posted on 2013-03-05 15:56  萌二&威比  阅读(1483)  评论(3编辑  收藏  举报

导航