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

时间:2017-07-10 18:33:29

标签: json swift swift4

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)

2 个答案:

答案 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"
 }
 */