Swift5中具有字符串值的JSONArray的JSONObject

dced5bon  于 2022-12-28  发布在  Swift
关注(0)|答案(1)|浏览(148)

我需要创建一个包含两个具有特定结构的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结构吗?

lx0bsm1f

lx0bsm1f1#

尝试这种方法,使用struct模型(MyObjectConfig)到...create a JSON Object containing two JSON Arrays with a specific structure。这个示例代码展示了如何将对象编码/解码为json。

struct MyObject: Codable {
             let config: [Config]
             let alarms: [[String: String]]
         }

         struct Config: Codable {
             let batteryState, maxHum, mode: String
             
             enum CodingKeys: String, CodingKey {
                 case batteryState = "battery_state"
                 case maxHum = "max_hum"
                 case mode
             }
         }

        // the (corrected) json data
        let json = """
        {"config": [{"battery_state": "3.12","max_hum":  "33","mode" : "mode"}], "alarms": [{"1": "12345678"}, {"2": "22334455"}]}
         """
        
        // initial empty myObject
        var myObject = MyObject(config: [], alarms: [])
        
        // json string to MyObject
        if let data = json.data(using: .utf8) {
            do {
                myObject = try JSONDecoder().decode(MyObject.self, from: data)
                print("---> myObject: \(myObject)")
            } catch {
                print("decode error: \(error)")
            }
        }
        
        // MyObject to json string
        do {
            let encodedData = try JSONEncoder().encode(myObject)
            let theJson = String(data: encodedData, encoding: .utf8)
            print("---> theJson: \(theJson!)")
        } catch {
            print(error)
        }

        // usage

        myObject.config.forEach{ conf in
            print("---> conf.batteryState: \(conf.batteryState)")
            print("---> conf.maxHum: \(conf.maxHum)")
        }
        
        myObject.alarms.forEach{ alarm in
            print("---> alarm: \(alarm)")
        }

相关问题