Detailed explanation of JSON to PLIST example developed by IOS

  • 2021-07-01 08:19:44
  • OfStack

IOS JSON to PLIST

Read the JSON data from the xx. json file and write it to the xx. plist file. The implementation code is as follows:


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]; 

Note: The above code snippet must run on the emulator

If you change the above code snippet to the following:


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]; 

Note: The city_province. json file copy has been transferred to the Supporting Files directory before testing

Test it on the simulator and print LOG as follows:


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

Test it on a real machine and print LOG as follows:


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

The path is correct, but the file cannot be found in the corresponding directory.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: