我以前能够序列化字典,但不知道如何序列化多个数据。
我想序列化歌曲信息,我将如何为多首歌曲执行此操作?我必须输出字符串的代码是:
NSArray *songs = [playlist items];
for (MPMediaItem *song in songs){
NSString *title =[song valueForProperty: MPMediaItemPropertyTitle];
NSString *artist =[song valueForProperty: MPMediaItemPropertyAlbumArtist];
NSString *album =[song valueForProperty: MPMediaItemPropertyAlbumTitle];
NSString *length =[song valueForProperty: MPMediaItemPropertyPlaybackDuration];
NSLog(@"Title: %@\nArtist: %@\nAlbum: %@\nLength: %@",title,artist,album,length);
}
我不知道如何在JSON中为每首歌分开这个。
答案 0 :(得分:1)
对于每个MPMediaItem
,创建一个NSDictionary
,其键/值对等于title
,artist
等。然后将每个值添加到一个可变数组中。最后,将数组序列化为JSON。例如:
NSMutableArray *mutableSongsToSerialize = [NSMutableArray array];
NSArray *songs = [playlist items];
for (MPMediaItem *song in songs){
NSString *title =[song valueForProperty: MPMediaItemPropertyTitle];
NSString *artist =[song valueForProperty: MPMediaItemPropertyAlbumArtist];
NSString *album =[song valueForProperty: MPMediaItemPropertyAlbumTitle];
NSString *length =[song valueForProperty: MPMediaItemPropertyPlaybackDuration];
NSDictionary *songDictionary = @{@"title": title, @"artist": artist, @"album":album, @"length":length};
[mutableSongsToSerialize addObject:songDictionary];
}
NSData *jsonRepresentation = [NSJSONSerialization dataWithJSONObject:mutableSongsToSerialize options:0 error:NULL];