2

I need to store JSON parsed data Into propertylist like below structure using objective C.

My JSON Response From Server :

{ 
   "response":{ 
      "A":{ 
         "name":"Arun",
         "age":"20",
         "city":"SFO",
         "subject":2
      },
      "B":{ 
         "name":"Benny",
         "age":"20",
         "city":"SFO",
         "subject":1
    },
      "C":{ 
         "name":"Nani",
         "age":"30",
         "city":"SFO",
         "subject":0
      }
   },
   "inprogressdata":{ 
   },
   "dataspeed":"112 milliseconds..."
}

I am trying like below storage method into propertylist. Into this propertylist Item 0 , 1, 2 Its called JSON response A, B, C values Into Array and Item should as a Dictionary.

NOTE : The A, B, C values will Increase based on JSON response , I mean Its not static It will go upto Z may be.

enter image description here

Into this Array values first thing every values should store as a dictionary. Within that dictionary need to add string values like below and If subject count above 0 based on that count It should create Array of dictionary like below Image.

enter image description here

For example :

-Root 
|
|-----Objects [Array Value]
       |
       |------Item 0(A) [Dictionary Value]   
       |
       |------name (String)
       |------age (String)
       |------city (String)
       |------subject (Number)     // If number 2 then need to create "Objects_Subjectcount" [Array Values]
       |------Objects_Subjectcount (Array)
             |
             |------Item 0 [Dictionary Value]
             |------Item 1 [Dictionary Value]    
SteaveJobs
  • 33
  • 2
  • 8
  • 2
    please read this for your answer [enter link description here](http://stackoverflow.com/questions/15526086/write-json-response-to-plist-file) – Jaydeep Patel Dec 28 '15 at 07:05
  • Its not helping because I have done plist creation and storage retiveal process. I need to store data like above strecture ex:array of dictionary then based on signal count need to create again array of dictionary nexted form. @iOS learner – SteaveJobs Dec 28 '15 at 07:08
  • Check out these links : [link1](http://stackoverflow.com/questions/905542/how-to-write-data-in-plist) [link2](https://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/) [link3](http://stackoverflow.com/questions/7628372/how-to-write-a-data-in-plist) and [Google search](https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=writing%20data%20to%20plist%20in%20ios). Read these and code as per you need to write into plist. – nikhil84 Dec 28 '15 at 07:17
  • @Nikhil84 Its all about plist, Thats not a matter man. I need how to store datas like above structure! – SteaveJobs Dec 28 '15 at 07:23

2 Answers2

2
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);

// get documents path
NSString *documentsPath = [paths objectAtIndex:0];

// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// set the variables to the values in the text fields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: @"pradip", @"25",@"Ahmedabad",@"Computer-Science", nil] forKeys:[NSArray arrayWithObjects: @"Name", @"AGE",@"CITY",@"Subject", nil]];

// create NSData from dictionary
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists

if(plistData) {

    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];

} else {

    NSLog(@"Error in saveData: %@", error);

}
Bista
  • 7,869
  • 3
  • 27
  • 55
pradip kikani
  • 627
  • 6
  • 14
  • I was curious about why you need to use `NSPropertyListSerialization`, instead of just calling `-writeToFile:atomically:` on `plistDict` directly. Then I found this article explaining the advantages of `NSPropertyListSerialization`: https://www.bignerdranch.com/blog/property-list-seralization/ – Nicolas Miari Dec 28 '15 at 08:10
2

Try this code

NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSDictionary *response = JSON[@"response"];
NSArray *objects = [response allValues];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"File.plist"];
NSError *writeError = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:objects format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
    [plistData writeToFile:plistPath atomically:YES];
}
else {
    NSLog(@"Error in saveData: %@", error);
}

If my understanding of your question's second part is correct, the code will be like this

NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
 NSDictionary *response = JSON[@"response"];
 NSArray *keys = [response allKeys];

 NSMutableArray *objects = [NSMutableArray new];
 for (NSString *key in keys) {
     NSMutableDictionary *object = response[key];
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subject = %@",object[@"subject"]];
     NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
     NSInteger subjects = [object[@"subject"] integerValue];
     if (subjects > 0) {

         NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
         [object setObject:Objects_Subjectcount forKey:@"Objects_Subjectcount"];
         for (NSInteger i = 0; i < subjects; i++) {
             [Objects_Subjectcount addObject:object];// object or anything you need

         }
     }
     [objects addObject:object];
 }

 NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsPath = paths.firstObject;
 NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"File.plist"];
 NSError *writeError = nil;
 NSDictionary *finalDict = @{@"Objects": objects};
 NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
 if(plistData){
     [plistData writeToFile:plistPath atomically:YES];
 }
 else {
     NSLog(@"Error in saveData: %@", error);
 }

The steps are,

1. Create JSON with mutable containers and leaves.
2. Iterate through all keys and values.
3. Check whether the subject value of object is greater than 0 in the existing subjects array? if yes add the object to
Objects_Subjectcount. Add the object to objects array.(Don't forget
to set an NSMutable array with key Objects_Subjectcount) to the
object. 4 . Make final dictionary to be written as plist - wrap the
objets array in a dictionary with key "objects"
5. Convert the dictionary to plist data and write it
Johnykutty
  • 12,091
  • 13
  • 59
  • 100
  • Its nice answer btw how can I see stored data's? – SteaveJobs Dec 28 '15 at 09:04
  • that will be in plistPath. If you are running in simulator, print(nslog) plistPath and in finder press shift+cmd+G then past this path and enter – Johnykutty Dec 28 '15 at 09:06
  • OMG! Its storing automatically everything! WOW Awesome @JohnyKutty! – SteaveJobs Dec 28 '15 at 09:12
  • BTW I asked another on based on subject count need to add nested array of dictionary Items @JohnyKutty – SteaveJobs Dec 28 '15 at 09:14
  • You meant if there is more items in the dict with same subject, it should not add in the root and should be added to the same dictionary, with the key Objects_Subjectcount? – Johnykutty Dec 28 '15 at 09:27
  • Its totaly wrong buddy. See first method is OK. In that methode we can see A B C items like item 0 1 2...Into that dictionary we can see subject count number If that number above 0 for example : 2 then Its automattically create under the subject one root array within that array 0 1 2 Items it means subjects. You can see my posted second Image! – SteaveJobs Dec 28 '15 at 10:05
  • you men its the count of subjects? then what will be added to Objects_Subjectcount array? – Johnykutty Dec 28 '15 at 10:20
  • U can see now Image 2 on posted above Red and blue marked! The Object_subject count Inside just need to create array Items I will add another data into that latter. Now based on count value I need to create Object_Subjectcount Array of dictionary items for every main array items @Johnykutty – SteaveJobs Dec 28 '15 at 10:31
  • Super brother. Thank you so much!@JohnyKutty – SteaveJobs Dec 28 '15 at 10:51
  • I have last doubt need to add "isParent - Boolean value" into Item 0,1,2,3,etc,.. and within subject count need to add "ischild - Boolean value" Its I need to add by hardcore @JohnKutty – SteaveJobs Dec 28 '15 at 15:14
  • please help me dude Its not completed http://stackoverflow.com/questions/34504602/how-to-add-new-keys-and-values-into-plist-using-objective-c – SteaveJobs Dec 29 '15 at 06:39