0

I'm trying to parse complex JSON file in Swift 3. I'm having trouble with getting values. I found some sample code and tried to tweak it a bit but it doesn't work I currently get an error "Type "NSArray?" has no subscript members"... I'm not even sure this is the right way to do it. Attaching JSON screenshot any advice on how to properly parse it really appreciated.

Here's my current code:

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

let mainlistJson = jsonResult["mainlist"]as? NSArray

if let items = mainlistJson["items"] as? NSArray 
{
for item in items {
 if let description = item["description"]as? String {
 print(description)
}  } }

json sample

KirillC
  • 780
  • 2
  • 8
  • 21

1 Answers1

1

Don't use NSArray or NSDictionary in Swift. You should use the Arrays and Dictionaries of the Swift Standard Library.

For arrays, you could use: [Any]

For dictionaries: [String: Any]

Then you will be able to access the contents via subscripts.

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
  • Still get an error Type [Any]? has no subscript members – KirillC Dec 07 '16 at 15:42
  • @KirillC Read this: https://developer.apple.com/swift/blog/?id=37 – Eric Aya Dec 07 '16 at 15:46
  • This documentation gives overall info I'm able to get to second clause but I still get errors when I try to get to description.. most of the examples in other posts show more simple JSONs. mine has several layers and I just can't figure out code get those value... – KirillC Dec 07 '16 at 16:30
  • 2
    @KirillC There's nothing mysterious. Complex or not, JSON is only JSON. What I mean is that `[]` denotes an array, `{}` denotes a dictionary, `[{}, {}]` is an array of dictionaries, etc. That's all there is to know. If your JSON is complex it will require work for you to follow its logic - we can't do that for you. Learn your API and how it's structured, then use JSONSerialization and cast the results to the proper types, arrays or dictionaries. – Eric Aya Dec 07 '16 at 18:15