【问题标题】:how manipulate a NSDictionary generated by a json file in swift如何在swift中操作由json文件生成的NSDictionary
【发布时间】:2015-01-21 11:19:14
【问题描述】:

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

{
"length" : 0, 
"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,但没有任何结果

完成此操作后,我想再次转换 JSON 中的“最终”NSDictionary 以将其保存在文件中。

“最终”的 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”控制新元素的索引

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

【问题讨论】:

    标签: swift ios8


    【解决方案1】:

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

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

    【讨论】:

    • 嗨 Rob,我还不能理解 :(。我试过你说但没有结果。如何做一个新的 NSDictionary 最终将成为我的 JSON 文件
    • 见修订答案中的例子。
    • 不需要,谢谢。哈哈。见what should I do when someone answers my question?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多