user2955394 user2955394 - 1 month ago 11
iOS Question

How to convert class object to json string in objective c

1.I create class objects then add value to my class with this code

csJastorPollQuestion *pq = [[csJastorPollQuestion alloc] initWithID:@"01" Name:@"AAA"];

2.I shown "csJastorPollQuestion" in NSLog it's present

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

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.When I run my project it's shown error this

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

5.What is the right way for convert "csJastorPollQuestion" to json string?


The dataWithJSONObject:options:error: method only works on objects that NSJSONSerialization knows how to convert to JSON. That means:

  • The top-level object must be an NSArray or NSDictionary
  • Objects contained must be instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • Dictionary keys must be NSStrings
  • Numbers must not be infinite or NaN.

You need to convert to a dictionary or array representation to use this method.