請嘗試下面的代碼:
NSString* path = [[NSBundle mainBundle] pathForResource:@"JSON" ofType:@"json"];
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *object = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *dictionaryKey in object) {
Blog *oBlog = [[Blog alloc] init];
oBlog.blogDomain = [[object valueForKey:dictionaryKey] objectForKey:@"BlogDomain"];
oBlog.blogName = [[object valueForKey:dictionaryKey] objectForKey:@"BlogName"];
[array addObject:oBlog];
}
} else {
NSLog(@"Error in parsing JSON");
}
//Blog.h
#import <Foundation/Foundation.h>
@interface Blog : NSObject
@property (nonatomic, strong) NSString *blogDomain;
@property (nonatomic, strong) NSString *blogName;
@end
//Blog.m
#import "Blog.h"
@implementation Blog
@end
//JSON.json
{
"-KGN0p1I4YFI2YNOcbv3" : {
"BlogDomain" : "blg1",
"BlogName" : "n1"
},
"-KGN198bzC54opL47vUl" : {
"BlogDomain" : "blg2",
"BlogName" : "n2"
},
"-KGN66aqkhIxBAKTcFCx" : {
"BlogDomain" : "blg3",
"BlogName" : "n3"
}
}