提问人:kiran 提问时间:6/25/2022 最后编辑:kiran 更新时间:6/25/2022 访问量:105
如何将字典的<null>转换为空
How to convert <null> to null of dictionary
问:
如何将字典的参数转换为<null>
null
var params = [String: Any]()
params["name"] = nameValue?.count ?? 0 > 0 ? nameValue : NSNull()
params["id"] = idValue?.count ?? 0 > 0 ? idValue : NSNull()
params["time"] = timeValue?.count ?? 0 > 0 ? timeValue : NSNull()
上面的代码构造了参数。
Before
▿ 0 : 2 elements
- key : “name”
- value : <null>
▿ 1 : 2 elements
- key : “id”
- value : <null>
▿ 2 : 2 elements
- key : “time”
- value : <null>
后
name: null
id: null
time: null
答:
0赞
koen
6/25/2022
#1
这只是 app.quicktype.io 根据示例 json 生成的代码:
import Foundation
// MARK: - Test
struct Test: Codable {
let isValid: Bool
let name, place, date, notes: JSONNull?
enum CodingKeys: String, CodingKey {
case isValid = "is_Valid"
case name, place, date, notes
}
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
let input = """
{
"is_Valid": false,
"name": null,
"place": null,
"date": null,
"notes": null
}
""".data(using: .utf8)!
let test = try JSONDecoder().decode(Test.self, from: input)
print(test)
输出:
Test(isValid: false, name: nil, place: nil, date: nil, notes: nil)
评论
null
nil
var params = [String: Any?]()
?null
NSNull
null