2013-04-21 53 views
0

我有一组JSON字符串,其中每个JSON字符串都有一个键。现在,我想将这些JSON字符串存储在设备上,以便以后可以使用这些数据。 这里我没有在设备上存储任何对象。 我可以使用CoreData还是有其他选择吗? 在设备上存储JSON的最佳做法是什么?使用CoreData存储JSON字符串

+0

如果数据真的没有与其他对象的关系,你可以尝试使用的plist。你能展示你的JSON吗? – Anupdas 2013-04-21 14:40:15

+0

我的JSON会是这样的,{“status”:“success”,“userid”:“129”,“description”:“some description”}这样就会有很多JSON字符串需要存储在设备上。 – satyanarayana 2013-04-21 15:20:25

+0

如果您要创建与用户的关系,并且此信息最好使用CoreData或Sqlite。否则你可以存储json文件。我建议将它存储在plist中,因为与json相比,它更容易形成字典或数组,因此编辑它们然后再保存它,这需要更多的努力来保存它们。是否有任何其他信息需要存储。 – Anupdas 2013-04-21 15:31:42

回答

0

JSON只是为服务器和客户端(您的应用程序)之间的快速传输定义紧凑型数据格式。

你需要做的是将JSON数据从服务器解码为数据类型NSDictionary,NSArray,NSString ...然后如果你想存储它们,使用plist,sqlite或者CoreData来存储。

对于CoreData,您需要创建与JSON格式关联的实体。

例:“关键”:“值” - >的NSDictionary

+0

由于我只存储了一组JSON字符串,在CoreData,sqlite,file和plist中,哪个更适合使用? – satyanarayana 2013-04-21 15:09:43

+0

plist,最简单 – strong 2013-04-21 22:36:48

1

你也可以简单的JSON保存到一个文件,当你需要它旁边再反序列化。

0

如果你没有太多的数据存储,你可以使用plist或json。 Plist会更容易,如果你存储json,你需要多行代码。

创建一个DataHelper类,其中包含保存,添加,查找全部,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]; 
}