Swift如何更新(修改,删除,添加)JSON条目

时间:2016-10-17 20:16:12

标签: ios json swift

您好我需要一些帮助,我正在制作一个IOS应用程序,它从JSON API获取数据,然后在表格上显示结果,当我点击表格中的结果时,它会转到第二个视图控制器我正在展示细节。我想要做的是更新我在详细信息上显示的信息,通过从表中删除它们来删除JSON中的条目,并添加要保存在JSON上的新条目。

这是JSON结构:

      {
        _id: "57eec6c9dfc2fb03005c0dd0",
        ssid: "nonummy",
        password: "accumsan",
        lat: 29.39293,
        lon: 115.71771,
        summary: "curae nulla dapibus dolor vel est donec odio justo sollicitudin ut",
        __v: 0,
        likes: 1,
        unlikes: 0,
        bssid: "EF:CD:AB:56:34:12"
        },

我希望能够更新SSID,密码和摘要。

这是我用来从JSON获取结果并且运行良好的代码

代码:

       let url = URL(string:"https://fierce-peak-97303.herokuapp.com/api/wifi")!

       let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil {

            print(error)

        }else {

            if let urlContent = data {

                do {

                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                //print(jsonResult))

                    for item in(jsonResult as? NSArray)! {

                        let ssid = (item as? NSDictionary)?["ssid"] as? NSString

                        //print(ssid)

                    }
                    self.tableData = jsonResult as! NSArray

                    DispatchQueue.main.sync(execute: {
                    self.table.reloadData()
                    })

                }catch {

                    print("No Json Result Was Found")
                }

            }

        }
    }

    task.resume()

例如,如果我点击表格的一行,我希望能够更新密码。

2 个答案:

答案 0 :(得分:0)

我设法这样做:所有格式化为swift 3

       //declare parameter as a dictionary which contains string as key and  value combination.
    let parameters = ["ssid": newSSID.text!,"password": newPass.text!,"lat": newLat.text!,"lon": newLon.text!,"summary": newSum.text!] as Dictionary<String, String>

    //create the url with NSURL
    let url = URL(string: "https://fierce-peak-97303.herokuapp.com/api/wifi")

    //create the session object

    let session = URLSession.shared

    //now create the NSMutableRequest object using the url object

    let request = NSMutableURLRequest(url: url!)

    request.httpMethod = "POST"


    var err : NSError?
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
    }catch{
        print("error")
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")
        let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("Body: \(strData)")
        var err: NSError?
        do {
            var json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSDictionary

        }catch{

            print("JSON error")
        }

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            print(err!.localizedDescription)
            let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSDictionary

                if let parseJSON = json {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    let success = parseJSON["success"] as? Int
                    print("Success: \(success)")

                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                    print("Error could not parse JSON: \(jsonStr)")
                }

            }catch{

                print("JSON error")


            }

        }

答案 1 :(得分:-1)

您可以将json文件的内容作为您想要的任何数据结构获取,然后覆盖您想要更改的值,最后在您想要保存更改时覆盖原始文件:

所以你已经把JSON作为一个数组了:

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

let array = (jsonResult as? NSArray)!

所以现在你可以只更改数组中的值,当你完成所有你想要的改变后你可以覆盖json文件:(swift 3.0)

var jsonData: NSData!
// serialize json dataa
do 
{
    jsonData = try JSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions())
    let jsonString = String(data: jsonData as Data, encoding: String.Encoding.utf8)
    print(jsonString)
} 
catch let error as NSError 
{
    print("Array to JSON conversion failed: \(error.localizedDescription)")
}

// overwrite the contents of the original file.
do
{
    let file = try FileHandle(forWritingToURL: url!)
    file.writeData(jsonData)
        print("JSON data was written to the file successfully!")
}
catch let error as NSError
{
    print("Couldn't write to file: \(error.localizedDescription)")
}

我不确定写入服务器到底是如何工作的,但由于它是一个URL,我认为它的行为应该是一样的。

更新:

所以你原来的数组是:

let array = (jsonResult as? NSArray)!

您可以将其转换为类似的词典数组

var dictionaries : [[String: NSObject]] = array as? [[String: NSObject]]

你做了ssid:

int i = 0;
for (dictionary in dictionaries)
{
    let ssid = dictionary["ssid"]
    let newSSID = ssid + "something I want to edit my values with"

    // now we have our new value, so we update the array
   dictionaries[i]["ssid"] = newSSID
   i += 1
}

现在在此之后我们用新的字典对象覆盖原始文件,我在上面写了这个对象。