如何检查 json 返回值是数组还是字典的形式



我使用 swift 4 来处理从 URLSession 调用返回的 json。 调用后,JSON 将使用 URL 字符串作为键保存到字典(缓存类型(。然后,我想将 json 处理为一个名为 ApodJSON 的自定义对象。有时返回的 json 是我的 ApodJSON 对象的数组,有时它是一个 ApodJSON。

当我使用 swift 的新 JsonDecoder 时images = try JSONDecoder().decode([ApodJSON].self, from: data)如果 json 之前的代码返回了一个单独的对象,即"预期解码数组但找到了字典",我会收到一条错误消息。

如何检查 json 数据是 json 数据数组还是字典格式的单独项目,以允许我调用适当的 JSONDecoder 方法。以下检查数据是否为数组不起作用

    // 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)
    }
}
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)
        }
     }
}

最新更新