0

Hey I have the following JSON:

{
    "monuments": [
        {
            "name": "Iglesia de Tulyehualco",
            "description": "No hay descripción",
            "latitude": 19.2544877,
            "longitude": -99.012157
        },
        {
            "name": "Casa de Chuyin",
            "description": "Casa de Jesús",
            "latitude": 119.2563629,
            "longitude": -99.0152632
        }
    ]
}

I get the following code to try parse each object but I'm getting the error that type Any has no member 'x'.

func loadMonuments() {
    if let path = Bundle.main.path(forResource: "monuments", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let monumentsJson = jsonResult["monuments"] as? [Any] {
                for m in monumentsJson {
                    print(m)
                }
            }
        } catch {
            // handle error
        }
    }
}

I want to get each property of the monument.

2
  • What is the exact error and which line is actually causing the error? Commented Oct 3, 2018 at 23:35
  • it seems you want to access keys with print(m.name) Commented Oct 3, 2018 at 23:35

2 Answers 2

2

Option1:(recommended)

struct Root:Decodable { 
 let monuments:[InnerItem] 
}

struct InnerItem:Decodable { 
 let name:String
 let description:String
 let latitude:Doube
 let longitude:Double 
}

//

 do {
      let data = try Data(contentsOf: URL(fileURLWithPath: path), options:[])
      let content = try JSONDecoder().decode(Root.self,from:data)
      print(content)
 }
 catch {
  print(error)
 }

Option2:

if let jsonResult = jsonResult as? [String:Any] , let monumentsJson = jsonResult["monuments"] as? [[String:Any]] {
     for m in monumentsJson {
         print(m["name"])
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In Swift4 was introduced Codable for serialization, so you must try to make your objects Codable like this:

struct Monument: Codable {
  let name: String
  let description: String
  let latitude: String
  let longitude: String
}

And then you can parse the object using this:

func loadMonuments() -> [Monument] {
    guard let path = Bundle.main.path(forResource: "monuments", ofType: "json"),
       let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)  else {
        return []
    }

    do {
        return try JSONDecoder().decode([Monument].self, from: data)
    } catch {
        print("error: \(error)")
        return []
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.