我有一个带有多个对象的JSON数组,我不知道如何将" URL"标记作为nsarray或nsdictionary抓取,并在CollectionView中显示该图像URL。我无法更改JSON数据格式。我应该怎么做?
这是JSON响应的样子:
{
"error": false,
"data": [
{
"albumid": 2,
"albumtitle": "Album 2",
"images": [
{
"image": "Img2.jpeg",
"imageid": 11
},
{
"image": "vr4.jpg",
"imageid": 4
},
{
"image": "3purple b-ball.jpg",
"imageid": 3
}
]
},
{
"albumid": 3,
"albumtitle": "Album 3",
"images": [
{
"image": "vr2.jpg",
"imageid": 6
},
{
"image": "vr1.jpg",
"imageid": 5
}
]
},
{
"albumid": 4,
"albumtitle": "Album 4",
"images": [
{
"image": "vr1.jpg",
"imageid": 8
}
]
},
{
"albumid": 12,
"albumtitle": "My Album",
"images": [
{
"image": "img3.jpeg",
"imageid": 64
},
{
"image": "img4.jpeg",
"imageid": 63
},
{
"image": "img5.jpeg",
"imageid": 62
}
]
},
{
"albumid": 13,
"albumtitle": "Demo Album",
"images": [
{
"image": "img6.jpeg",
"imageid": 67
},
{
"image": "img7.jpeg",
"imageid": 66
},
{
"image": "img11.jpeg",
"imageid": 65
}
]
}
]
}
尝试这样的东西(数据是您从WebServer获得的NSDATA对象(:
NSError *jsonError = nil;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if(!jsonError){
NSArray *dataArray = [jsonData objectForKey:@"data"];
NSDictionary *albumDict = [dataArray objectAtIndex:0];
NSArray *imagesArray = [albumDict objectForKey:@"images"];
NSDictionary *imageDict = [imagesArray objectAtIndex:0];
NSString *imageURL = [imageDict objectForKey: @"image"];
}
当然,您必须将循环用于数组元素,此示例仅在元素0中使用。其他检查是否存在等等。
您可以创建一个模型来保存图像ID和URL。您在主模型(相册(中添加这些图像对象的数组。在Swift中,您的模型可能看起来像这样
class Album {
var albumId = ""
var albumTitle = ""
var albumImages = [AlbumImage]()
}
class AlbumImage {
var imageId = ""
var imageUrl = ""
}
希望这会有所帮助!
下载JSON文件后使用此代码。
NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *rootArray = rootDict[@"data"];
NSDictionary *subDict;
NSArray *subArray;
NSDictionary *tempDict;
for (int i=0; i<rootArray.count; i++) {
subDict = rootArray[i];
subArray = subDict[@"images"];
for (int j=0; j<subArray.count; j++) {
tempDict = subArray[j];
NSLog(@"%@",tempDict[@"image"]);
}
}
在jsonobjectserialization中 data 是nsdata对象下载了JSON文件。