JSON序列化歌曲信息

时间:2013-08-21 20:41:54

标签: ios objective-c nsjsonserialization

我以前能够序列化字典,但不知道如何序列化多个数据。

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

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中为每首歌分开这个。

1 个答案:

答案 0 :(得分:1)

对于每个MPMediaItem,创建一个NSDictionary,其键/值对等于titleartist等。然后将每个值添加到一个可变数组中。最后,将数组序列化为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];