简体   繁体   English

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

How can I see the output of the json ? 我怎样才能看到json的输出?

If I use print(json) the only thing I get is Optional(45 bytes) 如果我使用print(json) ,我唯一得到的是Optional(45 bytes)

The encode() method returns Data containing the JSON representation in UTF-8 encoding. encode()方法返回包含UTF-8编码的JSON表示的Data So you can just convert it back to a string: 所以你可以把它转换回一个字符串:

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

Output: 输出:

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

With Swift 4, String has a initializer called init(data:encoding:) . 使用Swift 4, String有一个名为init(data:encoding:) init(data:encoding:) has the following declaration: init(data:encoding:)具有以下声明:

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

Returns a String initialized by converting given data into Unicode characters using a given encoding . 返回通过使用给定encoding将给定data转换为Unicode字符而初始化的String


The following Playground snippets show how to use String init(data:encoding:) initializer in order to print a JSON data content: 以下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"}
 */

Alternative using JSONEncoder.OutputFormatting set to prettyPrinted : 使用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"
 }
 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM