lozflan
lozflan

Reputation: 853

How to check if json return value is in the form of an array or a dictionary

Im using swift 4 to process json returned from a URLSession call. the json is saved to a dictionary (cache of type ) after the call using the URL string as the key. I then want to process the json to a custom object called ApodJSON. Sometimes the json returned is an array of my ApodJSON object and other times its a single ApodJSON.

when i use swift's new JsonDecoder images = try JSONDecoder().decode([ApodJSON].self, from: data) I get an error message if the json previously code returned an individual object ie "Expected to decode Array but found a dictionary instead."

How can i check if the json data is an array of json data or an indiviual item in dictionary format to allow me to call the appropriate JSONDecoder method. The following check if data is Array doesn't work

    // parse json to ApodJSON class object if success true
func processJSON(success: Bool) {
    // get the data stored in cache dic and parse to json
    // data is of type Data
    guard let data = self.dataForURL(url: self.jsonURL), success == true else { return }
    do {
        var images: [ApodJSON] = []
        // check if data is an array of json image data or an indiviual item in dictionary format
        if data is Array<Any> {
            images = try JSONDecoder().decode([ApodJSON].self, from: data)
        } else {
            let image = try JSONDecoder().decode(ApodJSON.self, from: data)
            images.append(image)
        }
        for image in images {
            print("ImageUrls: \(String(describing: image.url))")
        }
    } catch let jsonError {
        print(jsonError)
    }
}

Upvotes: 1

Views: 920

Answers (1)

Santhosh R
Santhosh R

Reputation: 1568

func processJSON(success: Bool) {
     // get the data stored in cache dic and parse to json
     // data is of type Data
     guard let data = self.dataForURL(url: self.jsonURL), success == true else { return }
     var images: [ApodJSON] = []
     do {
       // try to decode it as an array first
         images = try JSONDecoder().decode([ApodJSON].self, from: data)
         for image in images {
            print("ImageUrls: \(String(describing: image.url))")
         }
     } catch let jsonError {
        print(jsonError)
        //since it didn't work try to decode it as a single object
        do{
           let image = try JSONDecoder().decode(ApodJSON.self, from: data)
           images.append(image)
        } catch let jsonError{
           print(jsonError)
        }
     }
}

Upvotes: 1

Related Questions