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

时间:2017-11-15 23:04:04

标签: arrays json dictionary swift4 json-deserialization

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

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

如何检查json数据是json数据的数组还是 dictionary 格式的单个项目,以允许我调用相应的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)
    }
}

1 个答案:

答案 0 :(得分:1)

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