[英]How to convert class object to json string in objective c
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];
當我運行我的項目時,它顯示錯誤
[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;
}
dataWithJSONObject:options:error:
方法僅適用於NSJSONSerialization
知道如何轉換為JSON的對象。 這意味着:
NSArray
或NSDictionary
NSString
, NSNumber
, NSArray
, NSDictionary
或NSNull
。 NSString
NaN
。 您需要轉換為字典或數組表示形式才能使用此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.