This question already has answers here:
Convert an iOS objective c object to a JSON string

(4 个回答)


5年前关闭。




如何转换 JSON 中的对象列表?我搜索了互联网,但我使用的所有方法都出错了。我需要将对象 coll 转换为字符串 json
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];

最佳答案

您可以使用 NSJSONSerialization 类将 JSON 转换为 Foundation 对象并将 Foundation 对象转换为 JSON。

在这里你可以检查它 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);

关于ios - 从对象到json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32369642/

10-14 14:50
查看更多