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

how manipulate a NSDictionary generated by a json file in swift

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

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

我想在 "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、Strings,但没有任何结果

执行此操作后,我想再次转换 JSON 中的 "final" 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"
    }
]
}

"length"控制新元素的索引

我没有更多的想法来做这个。提前致谢

如果你想修改字典,你可以让它可变:

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