我将Xcode更新为Xcode 9.3,Swift 4.1。 试图将模型对象转换为JSON给出了下面的数据
{"Email": "some("xxxxxx")", "Password": "some("xxxxxxx")"}
我正在使用JSONSeriliazer,Serilization代码位于
之下 if(requestObj != nil){
let json = JSONSerializer.toJson(requestObj!)
request.httpBody = json.data(using: .utf8)
}
答案 0 :(得分:0)
如果您尝试通过投射或String?
将Optional<String>
(String
)转换为非可选String(describing:)
,则结果字符串将为Optional("your string here")
。如果您需要使其按原样工作,则在将其插入JSON字符串之前,您必须将其转换为非可选值。
您可以考虑使用Codable
协议进行JSON操作。
在此示例中,您也不确定是否希望电子邮件和密码是可选的。
struct LoginRequest: Codable {
private enum LoginRequestKey: String, CodingKey {
case email = "Email"
case password = "Password"
}
var email: String
var password: String
init(email: String,
password: String) {
self.email = email
self.password = password
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LoginRequestKey.self)
self.email = try container.decode(String.self, forKey: .email)
self.password = try container.decode(String.self, forKey: .password)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: LoginRequestKey.self)
try container.encode(email, forKey: .email)
try container.encode(password, forKey: .password)
}
}
let encoder = JSONEncoder()
let decoder = JSONDecoder()
let request = LoginRequest(email: "xxxxxx", password: "yyyyyy")
let json = try! encoder.encode(request)
let object = try! decoder.decode(LoginRequest.self, from: json)
如果需要可选,只需使用try?