0

I have a JSON file with this person objects. Each person has different information. This is the structure of the JSON file.

[
  {
    "person": {
      "name": "Dani",
      "job": "Artist",
      "country": "FR",
      "sold": "992",
      "email": "Dani",
      "facebook": "Artist",
      "twitter": "Dani",
      "instagram": "Artist",
      "snapchat": "Dani",
      "photo": "Artist"
    }
  },
  {
    "person": {
      "name": "Alex",
      "job": "",
      "country": "TU",
      "sold": "992",
      "email": "Dani",
      "facebook": "Artist",
      "twitter": "Dani",
      "instagram": "Artist",
      "snapchat": "Dani",
      "photo": "Artist"
    }
  }
]

I was able to open the json file but I am not able to parse it. This is my code

 func lodData()
    {
        let data = NSData(contentsOfURL: url!)



        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            if let person = json["person"] as? [[String: AnyObject]] {
                for p in person {
                    if let name = p["name"] as? String {
                        names.append(name)
                    }
                }
            }
        } catch {
            print("error serializing JSON: \(error)")
        }

        print(names) 

    }

As result the names array still empty.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
User1238
  • 87
  • 8
  • You need to study this answer :- http://stackoverflow.com/questions/25621120/simple-and-clean-way-to-convert-json-string-to-object-in-swift – Mitul Marsoniya Jun 28 '16 at 12:11
  • @ei-captain-v2-0 This question is not specifically related to iOS. All methods are from Foundation. – Eric Aya Jun 28 '16 at 12:33
  • 1
    Structure's top level is an array. And person dictionary is wrapped with an unnecessary dictionary as well. – Desdenova Jun 28 '16 at 12:35

1 Answers1

1

person is [String: String] means dictionary not an array .. .you can do something like this

 if let data = json as? [[String: AnyObject]] {
      for p in data {
          if let person = p["person"] as? [String: String]{
              names.append(person["name"])
          }
       }
  }
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108