如何在目标C中将类对象转换为JSON字符串
1.我创建了类对象,然后使用此代码将值添加到我的类中
1.I create class objects then add value to my class with this code
csJastorPollQuestion *pq = [[csJastorPollQuestion alloc] initWithID:@"01" Name:@"AAA"];
2.我在存在的NSLog中显示了"csJastorPollQuestion"
2.I shown "csJastorPollQuestion" in NSLog it's present
#<csJastorPollQuestion: id = (null) { ID = 01; Name = AAA; }>
3.我使用此代码将"csJastorPollQuestion"转换为json字符串
3.I convert "csJastorPollQuestion" to json string with this code
NSData *jsd = [NSJSONSerialization dataWithJSONObject:pq options:NSJSONWritingPrettyPrinted error:&er];
NSString *jsonString = [[NSString alloc] initWithData:jsd encoding:NSUTF8StringEncoding];
4.运行项目时,显示为错误
4.When I run my project it's shown error this
[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
5.将"csJastorPollQuestion"转换为json字符串的正确方法是什么?
5.What is the right way for convert "csJastorPollQuestion" to json string?
dataWithJSONObject:options:error:
方法仅适用于NSJSONSerialization
知道如何转换为JSON的对象.这意味着:
The dataWithJSONObject:options:error:
method only works on objects that NSJSONSerialization
knows how to convert to JSON. That means:
- 顶级对象必须是
NSArray
或NSDictionary
- 包含的对象必须是
NSString
,NSNumber
,NSArray
,NSDictionary
或NSNull
的实例. - 字典键必须为
NSString
s - 数字不能为无限或
NaN
.
- The top-level object must be an
NSArray
orNSDictionary
- Objects contained must be instances of
NSString
,NSNumber
,NSArray
,NSDictionary
, orNSNull
. - Dictionary keys must be
NSString
s - Numbers must not be infinite or
NaN
.
您需要转换为字典或数组表示形式才能使用此方法.
You need to convert to a dictionary or array representation to use this method.