添加/编辑JSON数据iOS? [英] Add/Edit JSON data iOS?

查看:165
本文介绍了添加/编辑JSON数据iOS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从本地驱动器获取JSON数据。
效果很好



现在我想将我的JSON数据添加到同一个网址



我不想创建和替换以前的json文件



是否可以?



有没有简单的方法呢?

  NSURL * fileUrl = [NSURL URLWithString:@localDriveURL ]。 
// NSData * data = [NSData dataWithContentsOfFile:filePath];
NSData * data = [NSData dataWithContentsOfURL:fileUrl];
NSError *错误;

NSArray * json = [NSJSONSerialization JSONObjectWithData:data // 1
options:NSJSONReadingMutableContainers
error:& error];

NSArray * json2 = [json valueForKey:@locations];

for(int i = 0; i< json2.count; i ++){

}


解决方案

如果该文件是应用程序包的一部分,则无法对其进行任何更改。



一般来说,你确实要替换现有文件。



虽然你可以使用 NSFileHandle 要将额外的数据写入文件,它相对复杂并且相对可能会破坏JSON(当你犯一个索引错误或类似的东西时)。



你最好的选择是读取mutable中的数据(如你所示),然后修改并使用 NSJSONSerialization 再次转换回数据,然后将该数据保存到磁盘(替换原始数据)。 / p>

您当前的代码应该是:

  NSMutableArray * json = [ ... 

因为你正在使用的可变容器选项。



然后,您可以向数组添加一些新项目:

  [json addObject:@Stuff]; 
[json insertObject:@Other StuffatIndex:0];

然后重新保存:

  data = [NSJSONSerialization dataWithJSONObject:json options:nil error:& error]; 
[data writeToURL:fileUrl atomically:YES];


I am using the below code to fetch JSON data from my local drive. It works quite well

Now I want to add my JSON data to the Same URL

I don't want create and replace the previous json file

Is it possible??

Is there any easy way to do it??

NSURL *fileUrl=[NSURL URLWithString:@"localDriveURL"];
//NSData *data = [NSData dataWithContentsOfFile:filePath];
NSData *data=[NSData dataWithContentsOfURL:fileUrl];
NSError* error;

NSArray* json = [NSJSONSerialization JSONObjectWithData:data //1
                                                     options:NSJSONReadingMutableContainers
                                                       error:&error];

NSArray *json2=[json valueForKey:@"locations"];

for (int i=0; i<json2.count; i++) {

}

解决方案

If the file is part of the app bundle, you can't change anything about it.

Generally speaking you do want to replace the existing file.

While you could use NSFileHandle to write additional data into the file it is relatively complex and relatively likely to corrupt the JSON (when you make an indexing mistake or something like that).

Your best option is to read the data in mutable (as you are), then modify and use NSJSONSerialization to convert back to data again, then save that data to disk (replacing the original).

Your current code should really be:

NSMutableArray* json = [...

because of the mutable container option you're using.

You can then add some new items to the array:

[json addObject:@"Stuff"];
[json insertObject:@"Other Stuff" atIndex:0];

Then re-save:

data = [NSJSONSerialization dataWithJSONObject:json options:nil error:&error];
[data writeToURL:fileUrl atomically:YES];

这篇关于添加/编辑JSON数据iOS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆