如何在目标c中将类对象转换为json字符串

时间:2014-02-12 03:15:22

标签: ios objective-c json object xcode5

1.我创建了类对象,然后使用此代码

为我的类添加值
csJastorPollQuestion *pq = [[csJastorPollQuestion alloc] initWithID:@"01" Name:@"AAA"];

2.我在NSLog中显示“csJastorPollQuestion”它的存在

#<csJastorPollQuestion: id = (null) { ID = 01; Name = AAA; }>

3.我使用此代码将“csJastorPollQuestion”转换为json字符串

NSData *jsd = [NSJSONSerialization dataWithJSONObject:pq options:NSJSONWritingPrettyPrinted error:&er];
NSString *jsonString = [[NSString alloc] initWithData:jsd encoding:NSUTF8StringEncoding];

4.当我运行我的项目时,显示错误

[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

5.将“csJastorPollQuestion”转换为json字符串的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

我认为您应该将自己的对象反映到NSDictionary并使用NSJSONSerialization转换为JSON字符串。

从属性反映:

    - (NSDictionary *)dictionaryReflectFromAttributes
    {
        @autoreleasepool
        {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            unsigned int count = 0;
            objc_property_t *attributes = class_copyPropertyList([self class], &count);
            objc_property_t property;
            NSString *key, *value;

            for (int i = 0; i < count; i++)
            {
                property = attributes[i];
                key = [NSString stringWithUTF8String:property_getName(property)];
                value = [self valueForKey:key];
                [dict setObject:(value ? value : @"") forKey:key];
            }

            free(attributes);
            attributes = nil;

            return dict;
        }
    }

转换为JSON字符串:

    - (NSString *)JSONString
    {
        NSDictionary *dict = [self dictionaryReflectFromAttributes];
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        if (jsonData.length > 0 && !error)
        {
             NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
             return jsonString;
        }
        return nil;
    }

答案 1 :(得分:1)

dataWithJSONObject:options:error:方法仅适用于NSJSONSerialization知道如何转换为JSON的对象。这意味着:

  • 顶级对象必须是NSArrayNSDictionary
  • 包含的对象必须是NSStringNSNumberNSArrayNSDictionaryNSNull的实例。
  • 字典键必须为NSString s
  • 数字不得为无限或NaN

您需要转换为字典或数组表示才能使用此方法。