2017-06-02 67 views
0

我的JSON文件是這樣的:的iOS:將數據寫入到JSON文件編程

{ 
    "images": [ 
    "straight up kick.png", 
    "women kick.png", 
    "Taekwondo Kanji vertical.png", 
    "face kick3.png", 
    "flexibility.png", 
    "Punch.png", 
    "hook kick.png", 
    "front kick 2.png" 
] 
} 

我讀上面的JSON編程象下面這樣:

NSString *path = [[NSBundle mainBundle] pathForResource:@"generated" ofType:@"json"]; 
NSData *data = [NSData dataWithContentsOfFile:path]; 
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

NSMutableArray * jsonimages = [dict objectForKey:@"images"]; 
NSLog(@"images %@", jsonimages); 

我想添加更多的項目到數組命名作爲通過以編程方式寫入json文件的jsonimages。 JSON文件名是generated.json。

任何幫助,將不勝感激。

+0

你有什麼試過的?你的問題是在'dict'中添加對象(注意它不可變),'jsonimages'還是將它保存下來?因爲你不能寫入'[NSBundle mainBundle]'。 – Larme

回答

0
- (void)writeStringToFile:(NSString*)aString { 

    // Build the path, and create if needed. 
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString* fileName = @"generated.json"; 
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) { 
     [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil]; 
    } 

    // The main act... 
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO]; 
} 

- (NSString*)readStringFromFile { 

    // Build the path... 
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString* fileName = @"generated.json"; 
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName]; 

    // The main act... 
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding]; 
}