Json 当结构属性是可选的时,如何检测数据值是否为零
使用Codable解析数据不会失败 当我使用generic时,如果字段与我的对象字段不同,我希望解析失败Json 当结构属性是可选的时,如何检测数据值是否为零,json,swift,generics,codable,Json,Swift,Generics,Codable,使用Codable解析数据不会失败 当我使用generic时,如果字段与我的对象字段不同,我希望解析失败 struct someStruct: Codable { var name: String? var age: Int? } JSON : { "some_key": 123 } 您应该使用Codable解析数据,无论数据是否为零。在这之后,您可以像下面这样检查结构的nil值- if let name = yourStruct.name as? String {
struct someStruct: Codable {
var name: String?
var age: Int?
}
JSON :
{
"some_key": 123
}
您应该使用Codable解析数据,无论数据是否为零。在这之后,您可以像下面这样检查结构的nil值-
if let name = yourStruct.name as? String {
} else {
//nil
}
您可以在结构中使用
Codable
,在解析JSON数据时,由于结构中的属性是可选的,因此可以使用if let
安全地展开值。我提供了一个同样的示例
import Foundation
let jsonData = """
{
"some_key": 123
}
"""
let data = Data(jsonData.utf8)
struct someStruct: Codable {
var name: String?
var age: Int?
}
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(someStruct.self, from: data)
// Either use this
print(decodedData.name ?? "Name not specified")
// Or use this
if let name = decodedData.name {
// Name is not nil
// Sample Example
print(name)
}
else {
// Name is nil , Handle the situation accordingly
// Sample Example
print("Name not specified")
}
} catch {
print("Could not parse JSON Data")
}
因此,如果某个字段丢失,您希望
抛出
,但在指定该字段时继续,但nil
。
您需要实现自定义编码来解决此问题:
enum EncodingError: Error {
case missing
}
struct Struct: Codable {
let age: Int
let name: String?
enum CodingKeys: CodingKey {
case age
case name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// normal decoding
age = try container.decode(Int.self, forKey: .age)
// check if key exists or throw
guard container.contains(.name) else {
throw EncodingError.missing
}
name = try container.decode(String?.self, forKey: .name)
}
}
let correctData = """
{
"age": 34,
"name": null
}
""".data(using: .utf8)!
let failData = """
{
"age": 33
}
""".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let encoded = try decoder.decode(Struct.self, from: correctData) // succeeds
let fail = try decoder.decode(Struct.self, from: failData) // fails
} catch(let error) where error is EncodingError {
error
} catch {
error
}
如果字段不在JSONA中,我希望它失败;如果字段值为空,则它能够继续。如果您的语句与您自己的语句相矛盾。首先,如果字段(或键)不在JSON中,您希望失败。然后,您说如果字段值为nil,则希望继续(这与JSON中的字段不相同,因为只有在JSON中没有字段时,结构的属性值才会为nil)。请提供更多信息或重新表述您的问题。我使用的是泛型可编码结构,因此我需要知道是否已从JSON中获取所有字段