【问题标题】:define unknown value from JSON with Bool type使用 Bool 类型从 JSON 定义未知值
【发布时间】:2019-03-21 18:48:29
【问题描述】:

我想存储传感器的状态(真/假/未知),我创建了 php API 来返回 JSON 值而没有任何问题,但我无法存储空值,NULL 值(swift 中的值为零)在布尔变量中。在这种情况下,是否需要定义 var String 来存储 ON/OFF/Unknown 值,或者我可以使用 Bool var 来存储 true/false/nil

我用 Codable 定义 Struct

struct nodedata: Codable {
var nodeName: String
var nodeID: String
var temperature: Float
var humidity: Float
var relayStatus: Bool
var lightStatus: Bool
var hallStatus: Bool
var smokeStatus: Bool
var pirStatus: Bool
enum CodingKeys: String, CodingKey {
        case nodeName = "node_name"  //Custom keys
        case nodeID = "node_id"
        case temperature = "temp"
        case humidity = "hum"
        case relayStatus = "relay_status"
        case lightStatus = "light_status"
        case hallStatus = "hall_status"
        case smokeStatus = "smoke_status"
        case pirStatus = "pir_status"
    }
}

下面是存储从 JSON 获取的值的类

class DataManager {
    var nodes = [nodedata]()    // i write main code to store JSON only...
guard let data = data else { return }   // data get from URLSession
                        print(data)
                        let decoder = JSONDecoder()
                        self.nodes = try decoder.decode([nodedata].self, from: data)

我添加从服务器返回的 JSON

[
  {
    "node_name": "SVIN03",
    "node_id": "y2cfwecrw3hqznuxmfvf",
    "temp": 2132,
    "hum": 111,
    "pir_status": false,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  },
  {
    "node_name": "SVIN04",
    "node_id": "aj2w1aljw8nd65ax79dm",
    "temp": 0,
    "hum": 0,
    "pir_status": false,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  },
  {
    "node_name": "SVIN05",
    "node_id": "mwmfl2og2l8888fjpj2d",
    "temp": 999,
    "hum": 0,
    "pir_status": true,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  }
]

【问题讨论】:

  • 在 Swift 中,您可以使用 Bool? 变量。
  • 请举一个导致您出现问题的 JSON 示例
  • Swift 提示: 在您的情况下,无需声明 CodingKeys。改为设置decoder.keyDecodingStrategy = .convertFromSnakeCase。另外,在你的结构中使用let 而不是var
  • @AshleyMills 我在帖子中添加了来自服务器的 JSON 返回。我有疑问,如果传感器的值未知,我应该在 JSON 中返回什么?字符串类型还是布尔类型?
  • @AshleyMills 如果 PHP 返回字符串类型(开/关/未知)值,在 Xcode 中我定义字符串类型以获取状态。这是了解传感器 3 种状态的好方法吗?

标签: json swift codable


【解决方案1】:

如果您有传感器的三种状态,则使用布尔值不是一个好方法,而是可以使用整数标志,它告诉传感器状态。

【讨论】:

  • 你能给出一些代码示例吗?非常感谢
  • var lightStatus: Int 而不是 var lightStatus: Bool
猜你喜欢
  • 2019-08-12
  • 2020-10-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
相关资源
最近更新 更多