【问题标题】:How To Store JSON Parsed Data Into Plist Using Objective C?如何使用 Objective C 将 JSON 解析的数据存储到 Plist 中?
【发布时间】:2016-04-02 00:50:57
【问题描述】:

我需要将JSON 解析的数据存储到propertylist 中,如下面的结构,使用objective C

我的来自服务器的 JSON 响应:

{ 
   "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..."
}

我正在尝试将以下存储方法放入propertylist。进入这个属性列表Item 0 , 1, 2 它称为JSON 响应A, B, C 值进入数组和项目应该作为一个字典。

NOTE : A, B, C 值将根据 JSON 响应增加,我的意思是它不是静态的,它可能会上升到 Z。

进入这个Array 值的第一件事是每个值都应该存储为dictionary。在该字典中需要添加如下字符串值,如果基于该计数的主题计数高于 0 它应该创建字典数组,如下图所示。

例如:

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

【问题讨论】:

  • 请阅读本文以获取答案enter link description here
  • 它没有帮助,因为我已经完成了 plist 创建和存储 retiveal 过程。我需要像上面那样存储数据结构ex:字典数组然后根据信号计数需要再次创建字典nexted形式的数组。 @iOS 学习者
  • 查看这些链接:link1link2link3Google search。阅读这些和代码,根据需要写入 plist。
  • @Nikhil84 都是关于 plist 的,这不是问题。我需要如何存储上述结构的数据!

标签: ios objective-c json dictionary plist


【解决方案1】:

试试这个代码

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);
}

如果我对您问题第二部分的理解是正确的,代码将是这样的

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);
 }

步骤是,

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

【讨论】:

  • 它的好答案顺便说一句我怎样才能看到存储的数据?
  • 将在 plistPath 中。如果您在模拟器中运行,请打印(nslog)plistPath 并在查找器中按 shift+cmd+G 然后通过此路径并输入
  • 天啊!它自动存储一切!哇太棒了@JohnyKutty!
  • 顺便说一句,我问另一个基于主题计数需要添加字典项的嵌套数组@JohnyKutty
  • 您的意思是,如果字典中有更多具有相同主题的项目,则不应将其添加到根目录中,而应将其添加到同一字典中,键为 Objects_Subjectcount?
【解决方案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);

}

【讨论】:

  • 我很好奇为什么你需要使用NSPropertyListSerialization,而不是直接在plistDict 上调用-writeToFile:atomically:。然后我发现这篇文章解释了NSPropertyListSerialization的优点:bignerdranch.com/blog/property-list-seralization
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
相关资源
最近更新 更多