我正在尝试发送一系列字典,但验证失败。以下是输出示例:
{
album = "Karaoke - In the style of Goo Goo Dolls - Vol. 2";
artist = "Stingray Music (Karaoke)";
length = "208.404";
title = "Better Days (Karaoke Version)";
},
{
album = Down;
artist = "Jay Sean";
length = "212.61";
title = Down;
},
{
album = "Growing Pains";
artist = "Mary J Blige";
length = "301.844";
title = "Come to Me (Peace)";
}
以下是生成它的代码:
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];
}
NSString *jsonRepresentation = [NSJSONSerialization JSONOBjectWithData:mutableSongsToSerialize options:0 error:NULL];
我认为这行需要以某种方式进行修改,以便每首歌都不被视为根元素,但我不确定具体做什么。
NSDictionary * songDictionary = @ {@“title”:title,@“artist”:artist, @“专辑”:专辑,@“长度”:长度};
答案 0 :(得分:2)
您的JSON无效,您应该将:
代替=
和,
而不是;
,不要忘记省略最后'
。此外,必须引用散列键:
{
"album": "Karaoke - In the style of Goo Goo Dolls - Vol. 2",
"artist": "Stingray Music (Karaoke)",
"length": "208.404",
"title": "Better Days (Karaoke Version)"
},
...
您也可以使用JSON lint检查您的JSON。
答案 1 :(得分:2)
您没有使用正确的方法来序列化JSON。您需要使用+[NSJSONSerialization dataWithJSONObject:options:error]
。
这是一个使用与您相同的结构但具有硬编码值的示例:
NSDictionary *song1 = @{@"title": @"title1", @"artist": @"artist1", @"album":@"album1", @"length":@"length1"};
NSDictionary *song2 = @{@"title": @"title2", @"artist": @"artist2", @"album":@"album2", @"length":@"length2"};
NSDictionary *song3 = @{@"title": @"title3", @"artist": @"artist3", @"album":@"album3", @"length":@"length3"};
NSArray *songs = @[song1, song2, song3];
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:songs options:NSJSONWritingPrettyPrinted error:&error];
NSString *JSONDataAsString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(@"JSON String = %@",JSONDataAsString);
NSLog(@"error was %@",error);
输出如下:
JSON String = [
{
"title" : "title1",
"album" : "album1",
"length" : "length1",
"artist" : "artist1"
},
{
"title" : "title2",
"album" : "album2",
"length" : "length2",
"artist" : "artist2"
},
{
"title" : "title3",
"album" : "album3",
"length" : "length3",
"artist" : "artist3"
}
]
如果您不想添加Objective-C代码以查看字符串输出,可以在lldb中尝试以下操作:
expr (NSString *) [[NSString alloc] initWithData:JSONData encoding:4]
由于调试程序的可见性问题, 4
用于代替NSUTF8StringEncoding
。