确定“nil"JSON 中的值 [英] Determine "nil" value in JSON

查看:31
本文介绍了确定“nil"JSON 中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用从服务器接收 JSON 对象.并且对象中的某些字段可能会丢失,或者是 nil.所以,我需要在计算值之前找到它们.我有一个代码片段如下:

The app receives JSON object from the server. And some field in the object can be missing, or be nil. So, I need to find them before computing a value. I have a code fragment as below:

print(package["store"]!["cover"]) //here, console output: "nil"
if ((package["store"]!["cover"]) != nil) {
    //the 'if' statment above has no effect, statment below is executed,
    // and error occurs.
    imageName = STATIC_IMAGE_URL + (package["cover"] as! String)
}

如何检测响应 JSON 是否缺少某些字段或为零字段?

How can I detect if the response JSON has some missing or nil fields?

推荐答案

您可以使用 可选链可选绑定条件转换 组合在同一个 if-let 语句中:

You can use optional chaining, optional binding, and conditional casting combined in the same if-let statement:

if let cover = package["store"]?["cover"] as? String {
    imageName = STATIC_IMAGE_URL + cover
} else {
    imageName = "someDefaultImage"
}

它是这样工作的:

  • package["store"]?["cover"] 将返回 nil 如果 package["store"]package["store"]["cover"] 为零
  • 条件转换 as?如果左边的表达式不是 String
  • ,则 String 返回 nil
  • 最后,if-let 结构要么用实际的字符串填充 cover,要么在没有匹配的情况下进入 else 分支
  • package["store"]?["cover"] will return nil if either package["store"], or package["store"]["cover"] is nil
  • the conditional cast as? String returns nil if the expression to the left is not a String
  • finally the if-let construct will either populate cover with the actual string, or will go on the else branch if there's no match

这篇关于确定“nil"JSON 中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆