var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"
let encoder = JSONEncoder()
let json = try? encoder.encode(test)
我怎样才能看到的输出json
?
如果我使用print(json)
我得到的唯一东西是Optional(45 bytes)
var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"
let encoder = JSONEncoder()
let json = try? encoder.encode(test)
我怎样才能看到的输出json
?
如果我使用print(json)
我得到的唯一东西是Optional(45 bytes)
该encode()
方法返回Data
包含 UTF-8 编码的 JSON 表示。因此,您可以将其转换回字符串:
var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"
let encoder = JSONEncoder()
if let json = try? encoder.encode(test) {
print(String(data: json, encoding: .utf8)!)
}
输出:
{“标题”:“标题”,“描述”:“描述”}
在 Swift 4 中,String
有一个名为init(data:encoding:)
. init(data:encoding:)
有以下声明:
init?(data: Data, encoding: String.Encoding)
通过使用 given 将 given 转换为 Unicode 字符来返回一个已
String
初始化的.data
encoding
以下 Playground 片段展示了如何使用String
init(data:encoding:)
初始化程序来打印 JSON 数据内容:
import Foundation
var test = [String : String]()
test["title"] = "title"
test["description"] = "description"
let encoder = JSONEncoder()
if let data = try? encoder.encode(test),
let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
/*
prints:
{"title":"title","description":"description"}
*/
替代使用JSONEncoder.OutputFormatting
设置为prettyPrinted
:
import Foundation
var test = [String : String]()
test["title"] = "title"
test["description"] = "description"
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let data = try? encoder.encode(test),
let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
/*
prints:
{
"title" : "title",
"description" : "description"
}
*/