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.

3
  • You need to study this answer :- stackoverflow.com/questions/25621120/… Commented Jun 28, 2016 at 12:11
  • @ei-captain-v2-0 This question is not specifically related to iOS. All methods are from Foundation. Commented Jun 28, 2016 at 12:33
  • 1
    Structure's top level is an array. And person dictionary is wrapped with an unnecessary dictionary as well. Commented Jun 28, 2016 at 12:35

1 Answer 1

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"])
          }
       }
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.