【问题标题】:How to fetch json data using url and write it in file?如何使用 url 获取 json 数据并将其写入文件?
【发布时间】:2013-02-08 09:27:23
【问题描述】:

正如我上面的屏幕截图,我的应用程序中有一个 json 文件 (productDetail.json),然后我从 json 数据写入文件,如下代码所示

else if([(MultipleURLConnection *)connection tag]==2)
    {
  if([fn writeToFile:responseData fileName:@"productDetail.json"])
       [self performSelector:@selector(loadingJSON) withObject:nil afterDelay:0.1];
    }

在上面的代码中,responseData 是 NSMutableData,fn 是函数类对象名称,我有下面的方法

- (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName 
 {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:myFile])  // if file doesn't exist, create it
    return ([fm createFileAtPath:myFile contents:data attributes:nil]);
else
    return ([data writeToFile:myFile atomically:YES]);  
 }

现在我决定从应用程序中删除 json 文件并将其放在服务器上然后获取它。所以在将 json 文件放在服务器上后我尝试像下面的编码一样获取它

else if([(MultipleURLConnection *)connection tag]==2)
    {
        NSURL *url = [NSURL URLWithString:@"http://mysite.com/Infomist/productDetail.json"];
        NSData *jsonData = [NSData dataWithContentsOfURL:url];

        if(jsonData != nil)
        {
            NSError *error = nil;

            id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
            if (error == nil)
              NSLog(@"show data %@",result);
       }

现在上面的方法成功地从服务器获取我的数据,它在 NSlog 中显示了我的所有数据,但对我来说现在的问题是现在如何修改这个方法

     if([fn writeToFile:responseData fileName:@"])

因为将json文件放在服务器上后,我没有任何文件可以在上述方法中传递文件名来调用

- (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName  .

我已经有本地 json 文件的应用程序流,所以我只需要在我的应用程序中写入 json 数据。

【问题讨论】:

    标签: iphone json ios6 nsdocumentdirectory


    【解决方案1】:
    - (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName 
    

    以上需要NSData作为参数

            id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    

    上面给出id作为返回类型对象..你需要检查它使用的是哪种类型的对象isKindOfClass

    然后使用解码/NSkeyedArchiver 或其他技术将其转换为数据

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2021-10-15
      相关资源
      最近更新 更多