Swift Codable空处理 [英] Swift Codable null handling

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

问题描述

我有一个使用Codable解析JSON的结构.

I have a struct that parse JSON using Codable.

struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}

现在,如果数量值变为null,则JSON解析失败.

Now if the amount value is coming as null the JSON parsing is failing.

所以我应该为Student结构中存在的所有IntDouble手动处理空情况吗?

So should I manually handle the null cases for all the Int and Double that are present in the Student struct?

String值为null的值将被自动处理.

The String values coming as null is automatically handled.

推荐答案

让我为您做一个游乐场,因为一个示例向您展示了一百多个单词:

Let me do this Playground for you since an example shows you more than a hundred words:

import Cocoa

struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}

let okData = """
{
   "name": "here",
 "amount": 100.0,
 "adress": "woodpecker avenue 1"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let okStudent = try decoder.decode(Student.self, from:okData)
print(okStudent)

let nullData = """
{
   "name": "there",
 "amount": null,
"adress": "grassland 2"
}
""".data(using: .utf8)!

let nullStudent = try decoder.decode(Student.self, from:nullData)
print(nullStudent)

如果使用可选选项定义结构,则

null可以很好地处理.但是,如果可以避免的话,我建议您不要这样做. Swift提供了我所知的最佳支持,可以帮助我 not 忘记处理nil可能发生的任何情况,但是仍然很痛苦.

null is handled just fine if you define your structs using optionals. I would however advise against it if you can avoid it. Swift provides the best support I know to help me not forgetting to handle nil cases wherever they may occur, but they are still a pain in the ass.

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

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