菜鸟教程小白 发表于 2022-12-11 17:52:07

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


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

<p>这是 JSON 结构:</p>

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

<p>我希望能够更新 SSID、密码和摘要。</p>

<p>这是我用来从 JSON 中获取结果的代码,并且运行良好</p>

<p>代码:</p>

<pre><code>       let url = URL(string:&#34;https://fierce-peak-97303.herokuapp.com/api/wifi&#34;)!

       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)?[&#34;ssid&#34;] as? NSString

                        //print(ssid)

                  }
                  self.tableData = jsonResult as! NSArray

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

                }catch {

                  print(&#34;No Json Result Was Found&#34;)
                }

            }

      }
    }

    task.resume()
</code></pre>

<p>例如,如果我单击表格的一行,我希望能够更新密码。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我设法做到了:所有格式都为 swift 3</p>

<pre><code>       //declare parameter as a dictionary which contains string as key andvalue combination.
    let parameters = [&#34;ssid&#34;: newSSID.text!,&#34;password&#34;: newPass.text!,&#34;lat&#34;: newLat.text!,&#34;lon&#34;: newLon.text!,&#34;summary&#34;: newSum.text!] as Dictionary&lt;String, String&gt;

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

    //create the session object

    let session = URLSession.shared

    //now create the NSMutableRequest object using the url object

    let request = NSMutableURLRequest(url: url!)

    request.httpMethod = &#34;POST&#34;


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

    request.addValue(&#34;application/json&#34;, forHTTPHeaderField: &#34;Content-Type&#34;)
    request.addValue(&#34;application/json&#34;, forHTTPHeaderField: &#34;Accept&#34;)

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

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

      }catch{

            print(&#34;JSON error&#34;)
      }

      // 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(&#34;Error could not parse JSON: &#39;\(jsonStr)&#39;&#34;)
      }
      else {
            // The JSONObjectWithData constructor didn&#39;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&#39;s get the value for &#39;success&#39; out of it
                  let success = parseJSON[&#34;success&#34;] as? Int
                  print(&#34;Success: \(success)&#34;)

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

            }catch{

                print(&#34;JSON error&#34;)


            }

      }
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Swift 如何更新(修改、删除、添加)JSON 条目,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40094922/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40094922/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Swift 如何更新(修改、删除、添加)JSON 条目