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)
答案 0 :(得分:5)
encode()
方法返回包含UTF-8编码的JSON表示的Data
。所以你可以把它转换回字符串:
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)!)
}
输出:
{"title":"title","description":"description"}
答案 1 :(得分:1)
使用Swift 4,String
有一个名为init(data:encoding:)
的初始化程序。 init(data:encoding:)
有以下声明:
init?(data: Data, encoding: String.Encoding)
使用给定的
String
返回通过将给定data
转换为Unicode字符而初始化的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"
}
*/