我有一组JSON字符串,其中每个JSON字符串都有一个键。现在,我想在设备上存储这些JSON字符串,以便以后可以使用这些数据。 在这里,我不会在设备上存储任何对象。 我可以使用CoreData还是有替代方案? 将JSON存储在设备上的最佳做法是什么?
答案 0 :(得分:1)
您也可以简单地将JSON保存到文件中,并在下次需要时再次反序列化。
答案 1 :(得分:0)
JSON只是定义紧凑的数据格式,以便在服务器和客户端(您的应用程序)之间快速传输。
你需要做的是将JSON数据从服务器解码为数据类型NSDictionary,NSArray,NSString ......然后如果你想存储它们,可以使用plist,sqlite或CoreData来存储。
对于CoreData,您需要创建具有JSON格式的实体关联。
Ex:“key”:“value” - >的NSDictionary
答案 2 :(得分:0)
如果您没有足够的数据存储,可以使用plist或json。 Plist会更容易,如果你存储json,你需要几行代码。
创建一个DataHelper类,其中包含save,add,findAll,findFirtWithValue:forObject:方法。
这是一个示例
#define kPlistFilePath @"Data.plist"
#define kJsonFilePath @"Data.json"
@implementation DataController
+ (NSString *)savedFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kPlistFilePath];
return filePath;
}
+ (NSArray *)findAll
{
NSString *filePath = [self savedFilePath];
return [NSArray arrayWithContentsOfFile:filePath];
}
+ (void)saveJSON:(id)object
{
NSString *filePath = [self savedFilePath];
NSArray *unsavedArray = nil;
if ([object isKindOfClass:[NSString class]]) {
NSError *error = nil;
unsavedArray = [NSJSONSerialization JSONObjectWithData:[object dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:&error];
}else if([object isKindOfClass:[NSArray class]]){
unsavedArray = object;
}else if([object isKindOfClass:[NSDictionary class]]){
unsavedArray = @[object];
}
if ([unsavedArray count]) {
[unsavedArray writeToFile:filePath atomically:NO];
}
}
+ (NSDictionary *)userInfoForID:(NSString *)userID
{
NSArray *allData = [self findAll];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid = %@",userID];
return [[allData filteredArrayUsingPredicate:predicate]lastObject];
}