Convert an iOS objective c object to a JSON string

后端 未结 4 1369
野趣味
野趣味 2020-11-29 05:34

I have an objective C class like,

@interface message : NSObject {
 NSString *from;
 NSString *date;
 NSString *msg;
}

I have an NSMutableAr

4条回答
  •  旧时难觅i
    2020-11-29 06:00

    Note: This will only work with serializable objects. This answer was provided above in an edit to the question itself, but I always look for answers in the "answers" section myself ;-)

    - (NSString*) convertObjectToJson:(NSObject*) object
    {
        NSError *writeError = nil;
    
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&writeError];
        NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
        return result;
    }
    

提交回复
热议问题