使用Bool类型从JSON定义未知值
我想存储传感器的状态(真/假/未知),我已经创建了php API来返回JSON值,没有任何问题,但我不能在Bool变量中存储空值,使用Bool类型从JSON定义未知值,json,swift,codable,Json,Swift,Codable,我想存储传感器的状态(真/假/未知),我已经创建了php API来返回JSON值,没有任何问题,但我不能在Bool变量中存储空值,NULLvalue(swift中为nil值)。在这种情况下,我是需要定义var字符串来存储开/关/未知值,还是可以使用Bool var来存储真/假/零 我用Codable定义Struct struct nodedata: Codable { var nodeName: String var nodeID: String var temperature: Float v
NULL
value(swift中为nil值)。在这种情况下,我是需要定义var字符串来存储开/关/未知值,还是可以使用Bool var来存储真/假/零
我用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
。改为设置解码器.keyDecodingStrategy=.convertFromSnakeCase。另外,在您的结构中使用let
,而不是var
@AshleyMills我在帖子中添加了来自服务器的JSON返回。我有一个问题,如果传感器的值未知,我应该以JSON返回什么?字符串类型还是Bool类型?@AshleyMills如果PHP返回字符串类型(开/关/未知)值,我在Xcode中定义字符串类型以获取状态。这是了解传感器3种状态的好方法吗?你能给出一些代码示例吗?非常感谢var-lightStatus:Int
而不是var-lightStatus:Bool
i.e。