2015-01-20 37 views
0

我有一个由JSON文件填充的NSDictionary。 JSON文件内容(最初)如何在swift中处理由json文件生成的NSDictionary

{ 
"length" : 0, 
"locations" : [] 
} 

我想在 “位置” 添加一些元素。该元素具有以下结构:

[ 
"name" : "some_name", 
"lat" : "4.88889", 
"long" : "5.456789", 
"date" : "19/01/2015" 
] 

在接下来的代码中,我读解JSON文件

let contentFile = NSData(contentsOfFile: pathToTheFile) 
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: nil, error: &writeError) as NSDictionary` 

就像你可以看到jsonDict包含JSON的信息,但在NSDictionary的对象。

在这一点上我不能添加之前提到的内容,我想插入的NSData,NSArray中,弦乐,并没有什么结果,我

做到这一点我想转换“最后”的NSDictionary在JSON一次储存后它在一个文件中。

“最终”的NSDictionary必须是这样的

{ 
"length" : 3, 
"locations" : [ 
    { 
    "name" : "some_name", 
    "lat" : "4.88889", 
    "long" : "5.456789", 
    "date" : "19/01/2015" 
    }, 
    { 
    "name" : "some_name_2", 
    "lat" : "8.88889", 
    "long" : "9.456789", 
    "date" : "19/01/2015" 
    }, 
    { 
    "name" : "some_name_3", 
    "lat" : "67.88889", 
    "long" : "5.456789", 
    "date" : "19/01/2015" 
    } 
] 
} 

“长度”控制新元素

索引我没有更多的想法做到这一点。在此先感谢

回答

0

如果你希望能够修改字典,你可以把它可变:

let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: .MutableContainers, error: &writeError) as NSMutableDictionary 

所得NSMutableDictionary可以修改。例如:

let originalJSON = "{\"length\" : 0,\"locations\" : []}" 
let data = originalJSON.dataUsingEncoding(NSUTF8StringEncoding) 
var parseError: NSError? 
let locationDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &parseError) as NSMutableDictionary 

locationDictionary["length"] = 1  // change the `length` value 

let location1 = [      // create dictionary that we'll insert 
    "name" : "some_name", 
    "lat" : "4.88889", 
    "long" : "5.456789", 
    "date" : "19/01/2015" 
] 

if let locations = locationDictionary["locations"] as? NSMutableArray { 
    locations.addObject(location1)  // add the location to the array of locations 
} 

如果你现在从更新locationDictionary构建JSON,它看起来像:

{ 
    "length" : 1, 
    "locations" : [ 
     { 
      "long" : "5.456789", 
      "lat" : "4.88889", 
      "date" : "19/01/2015", 
      "name" : "some_name" 
     } 
    ] 
} 
+0

喜罗布我不能听懂了没有:(我想你说的,但没有结果。 如何做一个新的NSDictionary终于将是我的JSON文件 – jhuazano 2015-01-21 01:20:04

+0

见例如,在修订后的答案。 – Rob 2015-01-21 03:21:43

+0

Thaks很多兄弟......它工作得很好 – jhuazano 2015-01-23 19:39:15

相关问题