如何操纵swift中json文件生成的NSDictionary

时间:2015-01-20 23:30:53

标签: swift ios8

我是一个由JSON文件填充的NSDictionary。 JSON文件内容(最初)

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

我想在" locations"中添加一些元素。元素具有以下结构:

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

在下一个代码中我读了de JSON文件

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

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

此时我无法添加前面提到的元素,我尝试插入NSData,NSArray,Strings,对我来说没什么结果

这样做之后,我想要转换" final"再次将JDS中的NSDictionary保存在文件中。

" final" 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"
    }
]
}

"长度"控制新元素的索引

我没有更多的想法来做这件事。提前谢谢

1 个答案:

答案 0 :(得分: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"
        }
    ]
}