使用Decodable进行JSON解析时,可选和decodeIfPresent有什么区别?

问题描述 投票:0回答:3

我第一次使用 Swift 4 中的

Codable
协议,我无法理解
decodeIfPresent
Decodable
的使用。

/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String?

这里建议如果值不与关联的键一起存在,则返回

nil
。如果这是唯一的原因,那么它与可选属性有何不同,因为如果响应中不存在值,可选变量也会设置为
nil

swift swift4 codable decodable
3个回答
108
投票

这两行代码之间有一个微妙但重要的区别:

// Exhibit 1
foo = try container.decode(Int?.self, forKey: .foo)
// Exhibit 2
foo = try container.decodeIfPresent(Int.self, forKey: .foo)

图表 1 将解析:

{
  "foo": null,
  "bar": "something"
}

但是不是

{
  "bar": "something"
}

而展览 2 会很乐意解析两者。因此,在

JSON
解析器的正常用例中,您需要为模型中的每个选项使用
decodeIfPresent


13
投票

我认为,如果您想使用 JSON 中可能缺少的属性的默认值,则使用

decodeifPresent
而不是可选属性更有意义。

例如,我们来看看 3 种情况:

1。所有键都存在于 JSON 中:

假设您必须解码此 JSON:

{
    "project_names": ["project1", "project2", "project3"],
    "is_pro": true
}

您可以使用这个结构:

struct Program: Codable {
    let projectNames: [String]
    let isPro: Bool
}

您将得到一个

Program
对象,其
isPro
值等于
true
。 (我想你的解码器
keyDecodingStrategy
在这个例子的其余部分是
.convertFromSnakeCase


2。 JSON 中缺少一些键,您可以在 Swift 中使用可选键:

{
    "project_names": ["project1", "project2", "project3"]
}

您现在可以使用这个结构:

struct Program: Codable {
    let projectNames: [String]
    var isPro: Bool?
}

您将得到一个

Program
对象,其
isPro
值等于
nil

如果 JSON 如下所示:

{
    "project_names": ["project1", "project2", "project3"],
    "is_pro": true
}

那么

isPro
将是一个具有值
Bool?
true
。 也许这就是您想要的,但您可能希望有一个默认值为
Bool
false
。这就是
decodeIfPresent
有用的地方。


3. JSON 中缺少一些键,并且您需要一个在 Swift 中具有默认值的非可选属性:

如果你的结构看起来像这样:

struct Program: Codable {
    let projectNames: [String]
    var isPro: Bool = false
}

如果 JSON 中不存在“is_pro”属性,您将收到解析错误。 因为 Codable 期望找到一个值来解析 Bool 属性。

在这种情况下,一个好主意是使用

decodeIfPresent
进行初始化,如下所示:

struct Program: Codable {
    let projectNames: [String]
    let isPro: Bool

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.projectNames = try container.decode([String].self, forKey: .projectNames)
        self.isPro = try container.decodeIfPresent(Bool.self, forKey: .isPro) ?? false
    }
}

这可以让您两全其美:

  • 你的结构体有一个
    Bool
    ,而不是
    Bool?
    属性
  • 您仍然可以解析不包含“is_pro”字段的 JSON
  • 如果 JSON 中不存在该字段,您可以获得默认值
    false

10
投票

是的,@Sweeper 的评论有道理。

我会尝试按照我的理解来解释。

public class User : Decodable{

    public var firstName:String
    public var lastName:String
    public var middleName:String?
    public var address:String
    public var contactNumber:String


    public enum UserResponseKeys: String, CodingKey{
        case firstName = "first_name"
        case lastName = "last_name"
        case middleName = "middle_name"
        case address = "address"
        case contactNumber = "contact_number"
    }

    public required init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: UserResponseKeys.self)

        self.firstName = try container.decode(String.self, forKey: .firstName)
        self.lastName = try container.decode(String.self, forKey: .lastName)
        self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName)
        self.address = try container.decode(String.self, forKey: .address)
        self.contactNumber = try container.decode(String.self, forKey: .contactNumber)
    }

}

上面是我的

User
类,其中我将
middleName
标记为可选参数,因为JSON响应可能不会提供
middleName
键值对作为响应,所以我们可以使用
decodeIfPresent

self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName)

而对于其他变量,它们是必填字段,因此我们确信不需要使用可选字段。我们仅使用

decode
,因为该方法不返回可选值。

public func decode(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String

上面的

decode
函数返回
String
,而
decodeIfPresent
返回
String?
,所以我们可以使用可选变量来存储它。

所以最终的结论是,如果您不确定服务响应合同,或者您可能会处理任何第三方服务,其中 JSON 响应和参数可能会在您不知情的情况下发生更改,那么您可以使用

decodeIfPresent
,这样它就可以处理缺少特定参数的情况响应并将值设置为
nil

© www.soinside.com 2019 - 2024. All rights reserved.