如何在Swift中处理json空值 [英] How To Handle json null values in Swift

查看:682
本文介绍了如何在Swift中处理json空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近两天我一直在使用JSON进行游戏,面临很多奇怪的问题,而且由于堆栈溢出,它对我有帮助.这是JSON功能键,具有两种类型的String值.

I am playing With JSON for last two days and facing alot of curious problems and thanks to stack overflow it helps me. This is JSON featured key has two types of String values.

 "featured":"1"

"featured": null,

我为解决这个问题做了很多尝试,但失败了

I tried a lot to handle this but failed

第1步:

 if dict.objectForKey("featured") as? String != nil {
    featured = dict.objectForKey("featured") as? String
    }

第2步:

    let null = NSNull()
    if dict.objectForKey("featured") as? String != null {
    featured = dict.objectForKey("featured") as? String
    }

第3步:

    if dict.objectForKey("featured") as? String != "" {
    featured = dict.objectForKey("featured") as? String
    }

但不幸的是找不到解决方案,您的回答将不胜感激.

but unfortunately can't found solution, you answer will be appreciated.

推荐答案

尝试一下

func nullToNil(value : AnyObject?) -> AnyObject? {
    if value is NSNull {
        return nil
    } else {
        return value
    }
}

object.feature = nullToNil(dict["feature"])

在这里,您可以使用此方法,它将空值转换为nil,并且不会导致应用程序崩溃.

Here, you can use this method, which will convert null value to nil and wont' cause crash in your app.

您还可以使用作为吗?

object.feature = dict["feature"] as? NSNumber

谢谢.

这篇关于如何在Swift中处理json空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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