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字符串的正确方法是什么?
我认为你应该将你自己的对象反映到 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)