ios - 获取 JSON 值到数组

标签 ios arrays json swift xcode

我需要从 MYSQL 获取 JSON 值并将其显示在 TableView 中。我已经完成了 PHP 部分来接收数据,但我的 XCODE 出现错误。我的数据将存储传感器的温度、湿度和数字状态(开关)。我有以下问题:

  1. 如何获取 ON/OFF JSON 值并将其存储在 Bool 数组中?
  2. 如何获取 JSON 值并存储在 Float 数组中?
  3. 如果 JSON 值为 ,如何在 XCODE 中将值存储为 0?
<小时/>
class DataManager {
  var nodenameArray: [String] = []
  var nodeidArray: [String] = []
  var tempArray: [Float] = []
  var humArray: [Float] = []
  var pirArray: [Bool] = []
  var lightArray: [Bool] = []
  var relayArray: [Bool] = []
  var hallArray: [Bool] = []
  var smokeArray: [Bool] = []

  @objc func taskdo() {
    self.nodenameArray = []
    self.nodeidArray = []
    self.tempArray = []
    self.humArray = []
    self.pirArray = []
    self.lightArray = []
    self.relayArray = []
    self.hallArray = []
    self.smokeArray = []

    if userlogin == true {
      let request = NSMutableURLRequest(url: NSURL(string: http://talectric.com/wp-admin/a_p/iot/read_all.php")! as URL)
        request.httpMethod = "POST"
        let postString = "username=\(username)&password=\(password)&authen=wdwfesf9329140dsvfxkciospdkm"

        request.httpBody = postString.data(using: String.Encoding.utf8)

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            if error != nil {
                print("error=\(error!)")
                return
            } else {
                do {
                    if let respondString = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                        print(respondString)
                        if let nodedata = respondString.value(forKey: "nodedata") as? NSArray {
                            for node in nodedata{
                                if let nodeDict = node as? NSDictionary {
                                    if let nodeid = nodeDict.value(forKey: "node_id") {
                                        self.nodeidArray.insert(nodeid as! String, at: 0)
                                    }
                                    if let nodeid = nodeDict.value(forKey: "node_name") {
                                        self.nodenameArray.insert(nodeid as! String, at: 0)
                                    }
                                    if let nodeid = nodeDict.value(forKey: "temp") {
                                        self.tempArray.insert(Float(nodeid as! String)!, at: 0)
                                    }
                                    if let nodeid = nodeDict.value(forKey: "hum") {
                                       print(nodeid)
                                        self.humArray.insert(Float(Int(nodeid as! String)!), at: 0)                
                                    }
                                }
                            }
                        }
                    }
                    print(self.nodenameArray)
                    print(self.nodeidArray)
                    print(self.tempArray)
                    print(self.humArray)
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
                }
                catch let error as NSError {
                    print(error.debugDescription)
                }
            }
        }
        task.resume()
    }
  }
}

以下是回复:

{
    nodedata =     (
            {

        "hall_status" = "<null>";

        hum = 111;

        "light_status" = "<null>";

        "node_id" = y2cfwecrw3hqznuxmfvf;

        "node_name" = SVIN03;

        "pir_status" = OFF;
        "relay_status" = "<null>";
        "smoke_status" = "<null>";
        temp = 2132;
    },
            {
        "node_name" = SVIN04;
        nodeid = aj2w1aljw8nd65ax79dm;
    },
            {
        "hall_status" = "<null>";
        hum = 100;
        "light_status" = "<null>";
        "node_id" = mwmfl2og2l8888fjpj2d;
        "node_name" = SVIN05;
        "pir_status" = ON;
        "relay_status" = "<null>";
        "smoke_status" = "<null>";
        temp = 45;
    }
);
numberofnodeid = 3;
}

111 100

Could not cast value of type '__NSCFNumber' (0x10db6f878) to 'NSString' (0x10ca71568). 2018-10-11 08:11:05.352491+0700 IOT 2[1506:101847] Could not cast value of type '__NSCFNumber' (0x10db6f878) to 'NSString' (0x10ca71568).

错误在这一行:

self.humArray.insert(Float(Int(nodeid as!String)!), at: 0)

最佳答案

首先在php中要查看json_decode来读取json数据

示例:

`$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // this will print 12345`

如何获取 ON/OFF JSON 值并将其存储在 Bool 数组中? 基本上你必须向 onOff 变量添加一个新值,例如

$onOff=array();
$val;
$obj = json_decode($json);
if (is_null($obj->{'name_of_the_alert'})) {
   $val = 0
} else {
   $val = $obj->{'name_of_the_alert'};
}
array_push($onOff,$obj->{'name_of_the_alert'});    

如何获取 JSON 值并存储在 Float 数组中? 基本上是一样的,我有一段时间没有使用 PHP,只是声明你需要的值类型的数组。

如果 JSON 值为 ,我如何在 XCODE 中将值存储为 0 ? 我猜你的意思是如果它为空,在这种情况下你必须这样做

$onOff=array();
$val;
$obj = json_decode($json);
if (is_null($obj->{'name_of_the_alert'})) {
   $val = 0
} else {
   $val = $obj->{'name_of_the_alert'};
}
array_push($onOff,$obj->{'name_of_the_alert'});

考虑到我可能会犯一些错误,因为我不熟悉较新的 PHP 版本。

祝你好运

关于ios - 获取 JSON 值到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52753089/

相关文章:

JSONSerialization 返回错误,但 php 解析器

ios - 有没有办法在 iOS 中检测正在运行的动画?

ios - ImageView 的 removeFromSuperview 和 .hidden 之间的区别

javascript - 我正在尝试将图像添加到选项卡栏项目但未加载

java - 检查数组是否对称

java - 不循环选择数组的所有元素

java - 如果我更改传递给 Arrays.asList(array) 的数组,列表值会更改

python - 在 Flask-sqlalchemy 和 Postgresql 中使用 JSON 类型

php - iOS 中图像未上传到服务器

javascript - JSON 中的多行元素?