17
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)

4

2 回答 2

28

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)!)
}

输出:

{“标题”:“标题”,“描述”:“描述”}
于 2017-07-10T18:38:51.210 回答
5

在 Swift 4 中,String有一个名为init(data:encoding:). init(data:encoding:)有以下声明:

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

通过使用 given 将 given 转换为 Unicode 字符来返回一个已String初始化的.dataencoding


以下 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"
 }
 */
于 2017-07-12T09:20:16.090 回答