1

我以前能够序列化字典,但不确定如何序列化多条数据。

我想序列化歌曲信息,我将如何为多首歌曲执行此操作?我必须输出字符串的代码是:

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 中将其分开。

4

1 回答 1

1

对于每个MPMediaItem,创建一个与,NSDictionary等价的键/值对。然后将每个添加到一个可变数组中。最后,将数组序列化为 JSON。例如:titleartist

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];
于 2013-08-21T20:44:35.440 回答