在 swift 中查看 JSONEncode() 输出的优雅方式

Elegant way to view JSONEncode() output in swift

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() 方法 returns 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)!)
}

输出:

{"title":"title","description":"description"}

对于 Swift 4,String 有一个名为 init(data:encoding:) 的初始化程序。 init(data:encoding:) 有以下声明:

init?(data: Data, encoding: String.Encoding)

Returns a String initialized by converting given data into Unicode characters using a given 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"
 }
 */