-3

I am using an api to get some data. The json has this data structure in one of its fields.

Here is the code to get access to my json:

let myUrl = NSURL(string:"http://openmensa.org/api/v2/canteens/\(choosenID)/days/" + currentDate + "/meals")!


    URLSession.shared.dataTask(with: myUrl as URL) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
                    print(json) 
                    for entry in json {
                        if let userId = entry["id"], let name = entry["name"], let category = entry["category"], let price = entry["prices"], let notes = entry["notes"] {
                            var meal = MealObject(id:userId as! Int, name:name as! String as! String, category:category as! String, price:0.0, notes: notes as! [String]);

                            print(price)
                                                           // DO MY OTHER STUFF...
                        }
                    }
                } else {
                    print("JSON is not an array of dictionaries")
                }
            } catch let error as NSError {
                print(error)
            }
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        }.resume()

print(json):

[["name": Macaroni & Cheese, "id": 2915045, "category": Tagesgericht 3, "prices": {
    employees = "2.6";
    others = "3.1";
    pupils = "<null>";
    students = "1.9";
}, "notes": <__NSArrayI 0x600000298380>(
Schwefeldioxid und Sulfite,
Senf,
Milch und Laktose,
Weizen,
Glutenhaltiges Getreide,
Alkohol,
mit Farbstoff
)
],

print(price):

{
    employees = "1.9";
    others = "2.4";
    pupils = "<null>";
    students = 1;
},
{
    employees = "2.6";
    others = "3.1";
    pupils = "<null>";
    students = "1.9";
}

I have no problem to get access to the id, the category, or the notes! The only problem are the prices.

How can I get access to this data structure? I want to save the double values to an array.

basti12354
  • 2,490
  • 4
  • 24
  • 43
  • There is no `id` or `prices` element in your object. What exactly do you want to do? Create three arrays? – Paulw11 Nov 26 '17 at 23:38
  • This isn't valid JSON (it's unclear what you mean by "print it"). Can you provide the actual JSON? This seems very broken; is `students` a string or a double? Is `pupils` a string or something else? – Rob Napier Nov 26 '17 at 23:40
  • @Paul I added some more information – basti12354 Nov 26 '17 at 23:48
  • Show us the whole JSON _as a string_, exactly as it arrives to you from the server. – matt Nov 27 '17 at 00:38
  • Use Codable and JSONDecoder (Swift 4), not JSONSerialization. – matt Nov 27 '17 at 00:38
  • 1
    `prices` is another object (dictionary), so retrieve it with `if let pricesDict = entry["prices"] as? [String:Any]`, then you can simply access `pricesDict["employees"]` or whatever – Paulw11 Nov 27 '17 at 01:31
  • 1
    You are showing bits and pieces. The first JSON you post shows what looks like 2 entries from a prices array. The second data looks like an Xcode dump of part of an array of something bigger, that includes a "prices" key with only one entry in the array. You haven't given us the full picture. Post all of your `json` data from your call to JSONSerialization – Duncan C Nov 27 '17 at 03:23
  • @DuncanC As I wrote "The json has this data structure in one of its fields. If I print it I get this output" -> The first output is the unknown datastructure inside the json and has the key "prices" -> let price = entry["prices"] -> then I print this: print[price] The second output was just the FIRST item of the whole json. The json contains hundreds of entries that all look exact like my example. – basti12354 Nov 27 '17 at 10:02

2 Answers2

0

Paulw11 delivered the answer in his comment:

My unknown data structure is a dictionary inside the json.

I changed my code from this:

if let userId = entry["id"], let price = entry["prices"]

to this:

if let userId = entry["id"], let price = entry["prices"] as? [String:Any]]

Now I can use it like this:

var employer = price["employees"]

Thanks to Paulw11;)

basti12354
  • 2,490
  • 4
  • 24
  • 43
  • Except that your first block of JSON shows an array containing 2 dictionaries, and your second block of JSON shows the object at the "prices" key as a single dictionary. You still haven't explained where those different fragments come from or why they are different. I guess it's possible that sometimes you'll get a single dictionary and other times you'll get an array of dictionaries, but that's bad. It would be much better to always get an array of 1 or more dictionaries. – Duncan C Nov 28 '17 at 00:23
  • @DuncanC Sorry I am so confused now ;) I edited my question now, maybe it is now clear what I have done! – basti12354 Nov 29 '17 at 10:58
-1

Did you try using "SwiftyJSON" Cocoapods? If not, I would recommend installing "SwiftyJSON" .Then its as easy as shown below

let json = data

let employees = json["employees"]
let others = json["others"]
let pupils = json["pupils"]
let students = json["students"]

if you are interested, you can go through this link https://cocoapods.org/?q=swiftyjs
You may need to go through this if you don't know about cocoapods usage or installation

911Rapid
  • 199
  • 3
  • 13