📅  最后修改于: 2023-12-03 14:53:49.364000             🧑  作者: Mango
在Swift 4中,可以使用JSONSerialization
类将字典转换为JSON序列化字符串。本文将介绍如何在Swift 4中将字典转换为JSON序列化字符串。
创建一个字典:
let dictionary = ["firstName": "John",
"lastName": "Doe",
"age": 25,
"email": "john.doe@example.com"]
将字典转换为JSON数据:
do {
let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
print(String(data: jsonData, encoding: .utf8)!)
} catch {
print(error.localizedDescription)
}
输出结果:
{
"firstName" : "John",
"age" : 25,
"lastName" : "Doe",
"email" : "john.doe@example.com"
}
可以使用JSONSerialization
类将JSON数据转换为字典:
let json = """
{
"firstName" : "John",
"age" : 25,
"lastName" : "Doe",
"email" : "john.doe@example.com"
}
"""
if let jsonData = json.data(using: .utf8) {
do {
if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
print(dictionary)
}
} catch {
print(error.localizedDescription)
}
}
输出结果:
["firstName": "John", "lastName": "Doe", "age": 25, "email": "john.doe@example.com"]
Swift 4中,可以使用JSONSerialization
类将字典转换为JSON序列化字符串。同时,还可以使用JSONSerialization
类将JSON数据转换为字典。