如何在Objective-C中将类对象转换为JSON字符串

3

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. 当我运行我的项目时,出现了以下错误信息:


this

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

5.如何正确将“csJastorPollQuestion”转换为JSON字符串?


把它放进字典里。JSON要求顶层对象必须是字典或数组。 - CodaFi
我想要一些例子,你能提供给我吗? - user2955394
2个回答

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
dataWithJSONObject:options:error:方法只能用于NSJSONSerialization知道如何转换为JSON的对象。这意味着:
  • 顶层对象必须是NSArrayNSDictionary
  • 包含的对象必须是NSStringNSNumberNSArrayNSDictionaryNSNull的实例。
  • 字典键必须是NSString
  • 数字不能是无限大或NaN

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接