2014-07-15 18 views
1

我基本上試圖找到一種方法來保存JSON服務器響應,因此即使服務器不再返回響應,也可以在依賴響應的某些應用邏輯上工作。當我取回數據,我可以把它打印出來,它會是這個樣子:保存一個JSON響應以用於調試

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

有什麼辦法,我可以創建一個使用該信息(NSData的dataWithData?)一個NSData的實例?或者有沒有辦法用JSON字符串創建JSON字典/數組?

TL; DR如何保存JSON服務器響應並添加調試選項來僞造服務器響應?

+0

你爲什麼不以一個txt文件保存,並將其添加到您的資源文件夾? – rishi

+0

如何將文本轉換回包含JSON的數組/字典? – user3490319

+0

檢查答案。 – rishi

回答

1

您可以直接保存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"]; 
} 

希望它能幫助。

乾杯。

0

你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 Simulator>應用程序> ProjectName>文件

0

將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執行所有操作,只要你想。

0

您可以將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]; 

}