-3

From this json i want to retrieve the values of the key "name" and "image"

  ["count": 12, "results": [{
        "pk": 6,
        "fields": {
            "name": "Kids Wear",
            "image": "[imag.jpg]",

        }

I have got error as **[ "Type 'Any' has no subscript members"] when i tried to get value using below code

let val = (json["results"]!)

val[0]["fields"] as [string:Any] 
Hamza Haider
  • 730
  • 6
  • 20
iosDev
  • 456
  • 4
  • 10

1 Answers1

1

You can try using Swift Codable class to get relevant data

private func getResponse() {
let json = "{count: 6,results: [{pk: 6,fields: {name: Ethnic Wear,image:[imag.jpg]}}]}"

let data = json.data(using: .utf8)
let jsonDecoder = JSONDecoder()
do {
    let response = try jsonDecoder.decode(Response.self, from: data!)
    guard let results = response.results else {
        return
    }

    let pk = results[0].pk ?? 0
    let fields = results[0].fields

} catch _ {

}
}

print(getResponse())

// Response.swift

import Foundation
struct Response : Codable {
       let count : Int?
       let results : [Results]?

}
iamVishal16
  • 1,780
  • 18
  • 40
  • if let json = try JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] { let data = json.data(using: .utf8) } got Error has Value of type[String:Any] has no member data – iosDev Aug 19 '19 at 06:54
  • But I am able to get the response? did you try it with Codable? – iamVishal16 Aug 19 '19 at 06:58
  • The CodingKeys and the `init(from` method are not necessary. If the struct members are optional the decoder calls `decodeIfPresent` implicitly. – vadian Aug 19 '19 at 07:03
  • Value of type '[String : Any]' has no member 'data' is my error when using the code let data = json.data(using: .utf8) – iosDev Aug 19 '19 at 07:03
  • @vadian sir, I know that already. – iamVishal16 Aug 19 '19 at 07:04
  • @iosDev `json` variable contains your JSON string response only and it's a `String` type variable. – iamVishal16 Aug 19 '19 at 07:39