我的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 :(得分: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];
}