2016-04-27 127 views
-1

我正在使用objective-c並試圖將JSON反序列化爲名爲Blog的自定義類的數組。所以下面的代碼應該生成三個對象並將它們添加到一個對象數組中。我看過this tutorial,但仍遇到問題。將Objective-C反序列化爲自定義對象的JSON

的JSON結構看起來是這樣的:

{ 
    "-KGN0p1I4YFI2YNOcbv3" : { 
    "BlogDomain" : "blg1", 
    "BlogName" : "n1" 
    }, 
    "-KGN198bzC54opL47vUl" : { 
    "BlogDomain" : "blg2", 
    "BlogName" : "n2" 
    }, 
    "-KGN66aqkhIxBAKTcFCx" : { 
    "BlogDomain" : "blg3", 
    "BlogName" : "n3" 
    } 
} 

任何幫助,將不勝感激。

回答

1

請嘗試下面的代碼:

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" 
} 
} 

enter image description here