0

I am trying to read a JSON output from a web app. This output is:

[{"group_name":"XYZ","adminof":0}]

I have a struct that looks like:

struct grouplistStruct{
var group_name : String
var adminof : Any
}

The code that I am using is:

let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{

          let loc = grouplistStruct(group_name: jsonResult["group_name"], adminof: jsonResult["adminof"])

I can see that jsonArray reads the value correctly. Similarly in the for loop, jsonResult is also reading the value correctly

But when I try to assign this value to a Struct variable, it shows an error:

Type 'Any' has no subscript members

Why is that happening? Sorry I am new to Swift so I am learning all this.

coderatlarge
  • 577
  • 3
  • 8
  • 23
  • Try `[[String: Any]]` instead of `[Any]` in this statement `try JSONSerialization.jsonObject(with: data, options: []) as! [Any]` – 3stud1ant3 Sep 24 '17 at 03:25
  • this works but what does this do? Can you throw some light? – coderatlarge Sep 24 '17 at 03:33
  • 1
    Please [search on the error](https://stackoverflow.com/search?q=%5Bswift%5D+Type+%27Any%27+has+no+subscript+members). This has been asked many, many times before. – rmaddy Sep 24 '17 at 03:58
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – Ssswift Sep 24 '17 at 04:43

1 Answers1

0

Since your json data is an array containing dictionaries like this:

[{"group_name":"XYZ","adminof":0}]

You are getting the error

Type 'Any' has no subscript members

because you are downcasting the json as an array of Any and in swift Any (as the name suggests) represents any type like Int, Double or Dictionary of type [String: String] as you know that Int or Double can not have subscript like someInt["subscript"]

So you need to downcast to this specific type using [[String: Any]] . This represents an array containing the dictionaries of type [String: Any]. This will work because dictionaries can have subscript members e.g someDict["group_name"]

Hence you should use [[String: Any]] instead of [Any] in this statement try JSONSerialization.jsonObject(with: data, options: []) as! [Any]

3stud1ant3
  • 3,586
  • 2
  • 12
  • 15