我需要创建一个包含两个具有特定结构的JSON数组的JSON对象。
下面是我需要的结果:
{"config": [{"battery_state" = "3.12","max_hum" = "33","mode" = "mode"}], "alarms": [{"1" = "12345678"}, {"2" = "22334455"}]}
我尝试使用NSMutableDictionary和Arrays,但结果不是我所期望的
let jsonConfigObject: NSMutableDictionary = NSMutableDictionary()
jsonConfigObject.setValue("33" as String, forKey: "max_hum" as String)
jsonConfigObject.setValue("3.12" as String, forKey: "battery_state" as String)
jsonConfigObject.setValue("mode" as String, forKey: "mode" as String)
let arrayConfig = [jsonConfigObject]
var jsonAlarmObject: NSMutableDictionary = NSMutableDictionary()
jsonAlarmObject.setValue("12345678" as String, forKey: "1" as String)
var arrayAlarms = [jsonAlarmObject]
jsonAlarmObject = NSMutableDictionary()
jsonAlarmObject.setValue("22334455" as String, forKey: "2" as String)
arrayAlarms.append(jsonAlarmObject)
let array = [["config" : arrayConfig], ["alarms" : arrayAlarms]]
结果如下:
[["config": [{"battery_state" = "3.12";"max_hum" = 33;mode = mode;}]], ["alarms": [{1 = 12345678;}, {2 = 22334455;}]]]
你知道我怎样才能得到这样的JSON结构吗?
1条答案
按热度按时间lx0bsm1f1#
尝试这种方法,使用struct模型(
MyObject
和Config
)到...create a JSON Object containing two JSON Arrays with a specific structure
。这个示例代码展示了如何将对象编码/解码为json。