How to convert class object to json string in c object

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

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

2. I showed "csJastorPollQuestion" in the NSLog that it represents

#<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 the project, it showed this error

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

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

+3
source share
2 answers

The method dataWithJSONObject:options:error:works only with objects that NSJSONSerializationcan convert to JSON. It means:

  • The top level object must be NSArrayeitherNSDictionary
  • NSString, NSNumber, NSArray, NSDictionary NSNull.
  • - NSString s
  • NaN.

.

+1

, 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;
    }
+2

All Articles