JSON序列化(如果API中为空或为空)

时间:2019-05-30 09:37:09

标签: json swift

嗨,我正在使用API​​在服务器上线之前从服务器中调用需求列表(称为可用性需求)。但是,当可用性需求为空时,它将使应用程序崩溃。

我已尝试使用修复程序将代码写在下面。 。可能还有其他方式可以编写此代码,但我希望仅使用JSON序列化。我已经检查了论坛,大多数都有较旧的代码。

    let rquirements = company.availabilityRequirements
    if rquirements != nil {
        let data = rquirements?.data(using: .utf8)!
        do {
            if let jsonArray = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [Dictionary<String,Any>]
            {
                print(jsonArray) //using the json here 
                for requirements in jsonArray {
                    let hist = AvailabilityRequirements(data: requirements)
                    availabitlityReqirements.append(hist)
                }
            } else { //where our error happens if nil
                print("Bad JSON Cannot Convert Value")
                return
            }
        } catch let error as NSError {
            print(error)
            return
        }

        for requirement in availabitlityReqirements {
            if requirement.required == 1{
                requirementItems.append(requirement.displayName)

            }
        }

如果可用性要求中有空白数据或缺少数据,我将尝试修复快速错误。我希望我能解决该问题,否则我想知道是否有人可以帮助我,如果我得到null不会崩溃。谢谢

1 个答案:

答案 0 :(得分:0)

您应该使用try?来避免错误。整个代码可以是:

if let rquirements = company.availabilityRequirements, 
    let data = rquirements.data(using: .utf8) {

    do {
        if let jsonArray = try? JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String: Any] {
            print(jsonArray) 

            for requirements in jsonArray {
                let hist = AvailabilityRequirements(data: requirements)
                availabitlityReqirements.append(hist)
            }
        }

    } catch let error as Error {
        print(error)
        return
    }

    for requirement in availabitlityReqirements {
        if requirement.required == 1 {
            requirementItems.append(requirement.displayName)
        }
    }

}