From object to json

How to convert a list of objects to JSON? I searched on the Internet, but all the methods that I used are wrong. I need to turn a coll object into a json string

Collections *current = _raccolte[_currentCell];
current.label = [[alertView textFieldAtIndex:0] text];
current.datetime_last_update = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];

NSMutableArray *coll = [[NSMutableArray alloc] init];
[coll addObject:current];
HttpClient *client = [[HttpClient alloc] init];
[client syncCollection:coll];
+4
source share
3 answers

You use the class NSJSONSerializationto convert JSON to Foundation objects and convert Foundation objects to JSON.

Here you can check it Link

Collections *current = _raccolte[_currentCell];
current.label = [[alertView textFieldAtIndex:0] text];
current.datetime_last_update = 
[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];

NSMutableArray *coll = [[NSMutableArray alloc] init];
[coll addObject:current.label];
[coll addObject:current.datetime_last_update];

NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:coll 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData 
                                             encoding:NSUTF8StringEncoding]; 

NSLog(@"JSON Output: %@", jsonString);
+1
source

There are many questions about json serialization: iOS JSON serialization for classes based on NSObject

, NSDictionary, jsonData​​strong > ( ) .

NSArray of NSDictionaries, :

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&writeError];

, , - :

NSString* jsonString = [[NSString alloc] initWithData:jsonData 
                                             encoding:NSUTF8StringEncoding];
+1

-, , . , Collections NSCoding. : (instancetype)initWithCoder:(NSCoder *)aDecoder void)encodeWithCoder:(NSCoder *)aCoder.

- (NSString*)convertObjectToJson:(NSObject *)object {
    NSError *error = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object 
                                                       options:NSJSONWritingPrettyPrinted 
                                                         error:&error];
    NSString *result = [[NSString alloc] initWithData:jsonData 
                                             encoding:NSUTF8StringEncoding];
    return result;
}

Collections NSMutableArray, NSCoding -compliant .

+1

Source: https://habr.com/ru/post/1605690/


All Articles