0

I have an array of JSON data from the following call:

guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [Any] else {
print("Not containing JSON")
return
}

when I run print(json) I get the following in the output:

[{
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-11-28T08:43:59";
STATUS = U;
"WIDGET_NUMBER" = K11;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}, {
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-05-09T08:46:23";
STATUS = U;
"WIDGET_NUMBER" = 89704;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}]

I am trying to get all of the WIDGETNUMBER values in the array of JSON data. The json variable is a Any type and I have not been able to convert to a struct so far. Is there an easy way to get the elements from the JSON objects?

Jacobi
  • 21
  • 1
  • 6

4 Answers4

2

It looks like you have an array of dictionaries

for item in json {
    if let item = item as? [String: Any],  let widgetNo = item["WIDGET_NUMBER"] {
        print(widgetNo)
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • When I tried this I got the error `Cast from '(String, JSON)' to unrelated type '[String : Any]' always fails` – jarrodwhitley Jun 22 '20 at 15:36
  • @Telarian JSON is not a built in type so I suppose you are using some 3rd party library. Probably you don't need to cast and should work with the JSON type directly but I can't help you with that. – Joakim Danielson Jun 22 '20 at 16:09
0

Your content is array of Dictionary, so that you must convert each element Dictionary to Json

for dic in content {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
        print(jsonData)
    } catch {
        print(error.localizedDescription)
    }
}

Or you can read value of WIDGET_NUMBER direct from Dictionary

for dic in content {
    print(dic["WIDGET_NUMBER"] ?? "Not found")
}
Keita Junichiro
  • 226
  • 2
  • 12
0

Joakim's answer is spot on for getting the widget number. For your struct, be sure to add something like this as an initializer to map your object.

let widgetNumber: Int
let user: String

    init?(json:[String:Any]) {

      guard let widgetNumber = json["WIDGET_NUMBER"] as? Int, 
            let user = json["CREATED_BY"] as? String else { return nil }

    self.widgetNumber = widgetNumber
    self.user = user

    }
Soh
  • 16
  • 2
0

If you just want an array of widget numbers you could use the reduce function which iterates the dictionaries in the array and extracts the widget numbers:

Using your data I put this in a storyboard:

let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [[String: Any]]

let widgetNumbers = json?.reduce(into: [String]()){ (accum, dict) in
    guard let widget = dict["WIDGET_NUMBER"] as? String else { return }
    accum.append(widget)
}

widgetNumbers // -> ["K11", "89704"]
Abizern
  • 146,289
  • 39
  • 203
  • 257