在Swift 3中很好地显示JSON数据

时间:2017-03-07 11:51:58

标签: swift

我对swift很新,我试图在3列中显示从服务器接收的JSON数据,但是,我希望文本排成行,并可能删除每个文本位周围的括号。我在下面附上了一张图片以及我的代码。

Swift Screenshot

   let u = UserDefaults.standard.value(forKey: "userIP")!
        var request = URLRequest(url: URL(string: "http://\(u):3000/logs")!)
        request.httpMethod = "POST"
        let postString = "LockID=\(lockid)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
                 DispatchQueue.main.async() {
                self.displayMyAlertMessage("response = \(response)")
                }
            }

            let responseString = String(data: data, encoding: .utf8)
         //   print("responseString = \(responseString)")

            if let data = responseString?.data(using: String.Encoding.utf8) {
                let resString = JSON(data: data)

                if resString["success"].stringValue == "true"
                {
                  //  save the data to be manipulated and stored in table somehow
                    let returned_name =  resString["message"].arrayValue.map({$0["name"].stringValue})
                    let returned_time =  resString["message"].arrayValue.map({$0["lockTime"].stringValue})
                    let returned_type =  resString["message"].arrayValue.map({$0["type"].stringValue})

                    DispatchQueue.main.async() {
                        self.updatename!.text = "\(returned_name.description)"
                        self.updateLock!.text = " \(returned_type.description)"
                        self.updateText!.text = " \(returned_time.description)"

                }

                }
                else if resString["success"].stringValue == "false"
                {
                     DispatchQueue.main.async() {
                    self.displayMyAlertMessage(resString["message"].stringValue)
                    }
                }

我使用SwiftyJSON操纵JSON数据。关于如何剥离[“”]的任何想法?

干杯

1 个答案:

答案 0 :(得分:0)

returned_name和其他returned...变量是由map函数引起的数组字符串。使用description方法打印数组会显示"[item1, item2, item3]"。要分别打印每个字符串,您需要重复循环。

  let returnedArray = resString["message"].arrayValue // you might cast the object to `[[String:Any]]`
  for item in returnedArray {
      print(item["name"])
      print(item["lockTime"])
      print(item["type"])
  }

要在表格视图中显示值,您需要一个模型,最好的方法是自定义结构

struct Item {
   let name : String
   let lockTime : String
   let type : String
}

然后创建一个数据源数组

var items : [Item]()

将收到的JSON映射到模型

  let returnedArray = resString["message"].arrayValue
  for item in returnedArray {
      let name = item["name"] ?? ""
      let lockTime = item["lockTime"] ?? ""
      let type = item["type"] ?? ""
      items.append(Item(name:name, lockTime:lockTime, type:type))
  }

将代码解析为viewDidLoad中的JSON,并在最后调用reloadData(),在cellForRow中获取数组中行的项并显示值,例如:< / p>

let item = items[indexPath.row]
self.updatename!.text = item.name
self.updateLock!.text = item.lockTime
self.updateText!.text = item.type

PS:因为你是Swift的新手,所以不要使用蛇案例变量名(returned_name),请使用驼峰案例(returnedName)。