Home > OS >  JSONObject of JSONArray with String values in Swift5
JSONObject of JSONArray with String values in Swift5

Time:12-28

I need to create a JSON Object containing two JSON Arrays with a specific structure.

Here is the result I would need:

{"config": [{"battery_state" = "3.12","max_hum" = "33","mode" = "mode"}], "alarms": [{"1" = "12345678"}, {"2" = "22334455"}]}

I tried to use NSMutableDictionary and Arrays but the result is not what I'm expecting

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]]

The result is the following:

[["config": [{"battery_state" = "3.12";"max_hum" = 33;mode = mode;}]], ["alarms": [{1 = 12345678;}, {2 = 22334455;}]]]

any idea how I can get such JSON Structure ?

CodePudding user response:

Don’t use old NS… classes instead create your dictionary in this way

let dictionary =
     ["config": [
        ["battery_state": "3.12", "max_hum": "33", "mode":"mode"]],
      "alarms": [
        ["1":"12345678"],["2": "223344455"]]
     ]

CodePudding user response:

Try this approach, using struct models (MyObject and Config) to ...create a JSON Object containing two JSON Arrays with a specific structure. This example code shows how to code/decode your object from/to 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)")
        }
  • Related