IOS JSON轉PLIST
從xx.json文件中讀取JSON數據,寫入到xx.plist文件中,實現代碼如下:
NSString *path = @"/Users/android_ls/Desktop/city_province.json"; NSArray *array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableLeaves error:nil]; [array writeToFile:@"/Users/android_ls/Desktop/city_province.plist" atomically:YES];
注:上面的代碼片段必須在模擬器上運行
若將上面的代碼片段改為如下:
NSString *path = [[NSBundle mainBundle] pathForResource:@"city_province.json" ofType:nil]; MyLog(@"path = %@",path); NSArray *array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableLeaves error:nil]; NSString *newPath = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] bundlePath],@"/city_province.plist" ]; MyLog(@"newPath = %@", newPath); [array writeToFile:newPath atomically:YES];
注:在測試前已將city_province.json文件copy到Supporting Files目錄下
放在模擬器上測試,打印LOG如下:
2014-10-15 22:38:03.224 YWBAPP[11578:60b] path = /Users/android_ls/Library/Application Support/iPhone Simulator/7.1/Applications/0909D47B-A2B6-467D-9E19-396A73383D8A/YWBAPP.app/city_province.json 2014-10-15 22:38:03.225 YWBAPP[11578:60b] newPath = /Users/android_ls/Library/Application Support/iPhone Simulator/7.1/Applications/0909D47B-A2B6-467D-9E19-396A73383D8A/YWBAPP.app/city_province.plist
放在真機上測試,打印LOG如下:
2014-10-15 22:40:59.796 YWBAPP[3127:60b] path = /var/mobile/Applications/4DAB17CC-F307-4D1B-B78D-80E9B5B4343F/YWBAPP.app/city_province.json 2014-10-15 22:40:59.805 YWBAPP[3127:60b] newPath = /var/mobile/Applications/4DAB17CC-F307-4D1B-B78D-80E9B5B4343F/YWBAPP.app/city_province.plist
路徑是對的,但是在相應的目錄下是找不到文件的。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!