Ios 保存JSON响应以用于调试目的

Ios 保存JSON响应以用于调试目的,ios,objective-c,json,Ios,Objective C,Json,我基本上是想找到一种保存JSON服务器响应的方法,这样即使服务器不再返回响应,也可以处理一些依赖于响应的应用程序逻辑。当我取回数据时,我可以将其打印出来,它将如下所示: <7b202254 7269704c 69737422 3a207b22 43757272 656e7454 696d6522 3a203134 30353037 33323836 ... 您可以直接将jsonData(NSData)保存到一个文件中,并使用它,请参见下文 { //Write NSData

我基本上是想找到一种保存JSON服务器响应的方法,这样即使服务器不再返回响应,也可以处理一些依赖于响应的应用程序逻辑。当我取回数据时,我可以将其打印出来,它将如下所示:

<7b202254 7269704c 69737422 3a207b22 43757272 656e7454 696d6522 3a203134 30353037 33323836 ...    

您可以直接将
jsonData
(NSData)
保存到一个文件中,并使用它,请参见下文

{
    //Write NSData directly to file
    [jsonData writeToFile:[self jsonFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];

    //Read from file
    NSJSONSerialization *json=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[self jsonFilePath]] options:0 error:nil];

    //The json object can be used as an Array or, Dictionary
    NSArray *array=(NSArray *)json;
    //OR
    NSDictionary *dic=(NSDictionary *)json;

}

-(NSString *)jsonFilePath{

   return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"file.json"];
}
希望能有帮助


干杯。

您的Json响应数据是图像数据。您可以将其存储在文档目录中,如下所示

        NSData *webData = UIImageJPEGRepresentation(image1, 0.5);

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

        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"Profile1.jpeg"];

        [webData writeToFile:savedImagePath atomically:YES];

现在在您的文档目录中存储图像。按照其他人的建议,选中转到Iphone模拟器>应用程序>项目名称>文档

将JSON存储在文本文件中

现在,您可以使用-

NSString *jsonFilepath = [[NSBundle mainBundle] pathForResource:@"jsonFile" ofType:@"text"];
// JSON Data
NSData *data = [NSData dataWithContentsOfFile: jsonFilepath];

// JSON String
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:jsonFilepath encoding:NSUTF8StringEncoding error:nil];

现在,您可以根据需要使用JSON执行所有操作。

您可以将JSON数据保存为应用程序文档文件夹中的plist

-(void)SaveResponse
{

NSError *error = nil;

        NSData *JSONData = Your Current Data that received from server

        NSMutableDictionary *objDictionary = [NSJSONSerialization
                                                  JSONObjectWithData:JSONData
                                                  options:NSJSONReadingAllowFragments
                                                  error:&error];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0];


     NSString *strFilePath = [documentsDirectory stringByAppendingPathComponent:@"Response.plist"];

     [objDictionary writeToFile:strFilePath atomically:YES];

}

为什么不保存一个txt文件并将其添加到资源文件夹?我如何将文本转换回包含JSON的数组/dict?@user3490319检查我的答案,了解如何将JSON作为数组或字典检索。