-1

I have a json saved in String format and I´m trying to use:

let json = "{'result':[{'name':'Bob','age':'27'}]}";

Using JSONSerialization comes error about Cannot invoke jsonOject with an argument...

if let json = try JSONSerialization.jsonObject(with: json) as? [String: Any],
   let array = json["result"] as? [[String: Any]] {
   for item in array {
       if let name = item["name"] as? String {
          if name == "Bob" {
             self.age = Int((item["age"] as? String)!)!
          }
       }
    }
}

I tryed to use this solution but with no success.

Vlad Davidchenko
  • 454
  • 1
  • 7
  • 24
user1801745
  • 391
  • 2
  • 18
  • If `json` is a `String` object, you need to convert it first into a `Data` object, because `jsonObject()` waits for a Data object, not a String one. Also, it's missing half the method, you are not writing "options" part. – Larme Sep 12 '17 at 18:29
  • 1
    @Larme The `options` parameter is optional. – vadian Sep 12 '17 at 18:31

1 Answers1

0

Please look at the declaration of jsonObject(with) by ⌥-click on the symbol.

The first parameter is of type Data so you have to convert String to Data.

A major issue is that the JSON is not formatted correctly. The string indicators must be double quotes.

let json = "{\"result\":[{\"name\":\"Bob\",\"age\":27}]}"
let jsonData = json.data(using: .utf8)
do { 
   if let result = try JSONSerialization.jsonObject(with: jsonData!) as? [String: Any],
   ...
   self.age = item["age"] as! Int
vadian
  • 274,689
  • 30
  • 353
  • 361