2013-08-21 56 views
1

我已经能够序列化字典之前,但不知道如何去序列化多个数据片段。JSON序列化歌曲信息

我想序列化歌曲信息,我该如何去做这个多首歌曲?我必须输出字符串的代码是:

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

转到json.org并研究JSON语法。大约需要10分钟才能学习。然后从Objective-C数组和字典进行转换是很简单的。 –

回答

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]; 
+0

一系列词典...哇,这很简单。我大大地推翻了它。谢谢 –

+0

不客气:) –