ios - 如何处理从 JSON 返回的 Null

标签 ios json swift

我有一个 JSON,它可能在某些键的值中包含 null 值。

这是我的代码:

static func parseJSONString(jsonString: String?, key: String?) ->  () -> String{
        var jsonSubString: String?
        func parseString() -> String{
            if let data = jsonString?.data(using: .utf8){
                if let content = try? JSONSerialization.jsonObject(with: data, options: []),
                    let array = content as? [[String: AnyObject]]
                {

                    for jsondict in array {
                        if let jsondictOptional = jsondict[key!]{
                            jsonSubString = (jsondictOptional as? String)
                        }
                        else {
                            jsonSubString = " "
                        }

                    }
                }
            }
            return jsonSubString!
        }
        return parseString
    }

当我运行应用程序时,它崩溃了。如何成功运行此代码,以便我什至可以处理从 JSON 返回的 nulls

最佳答案

崩溃的原因是你强行解包一个可选的。如果可选的是 nil,它会使您的应用程序崩溃。您可以通过让您的函数返回一个可选的 String 而不是强制展开它或在它为 nil 时返回一个空的 String 来修复它。

static func parseJSONString(jsonString: String?, key: String?) ->  () -> String? {
        var jsonSubString: String?
        func parseString() -> String{
            if let data = jsonString?.data(using: .utf8){
                if let content = try? JSONSerialization.jsonObject(with: data, options: []),
                    let array = content as? [[String: AnyObject]]
                {

                    for jsondict in array {
                        if let jsondictOptional = jsondict[key!]{
                            jsonSubString = (jsondictOptional as? String)
                        }
                        else {
                            jsonSubString = " "
                        }

                    }
                }
            }
            // Don't force unwrap this
            // You could use `return jsonSubString ?? ""` if you want an empty string if the value is null
            return jsonSubString
        }
        return parseString
    }

关于ios - 如何处理从 JSON 返回的 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650760/

相关文章:

ios - QLPreviewController 有时不显示文档

ios - 无法在 Storyboard的容器 View 内添加 TextView 名称

java - 如何将图像数组传递给 JSONObject?

json - PostgreSQL - 将行转换为 JSON 键/值对

java - Android中解析嵌套的Json对象并存储在数据库中

objective-c - 行代码在 lldb `p` 中工作,代码在托管单元测试中失败

ios - 为什么UIViewController中有一个navigationItem?

ios - 随机 UICollectionViewCell 大小

ios - Swift 中的 NSCoding 编码和解码 UITouchProperties

iOS 自动布局 : How to move views when label text gets longer