簡體   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)

我怎樣才能看到json的輸出?

如果我使用print(json) ,我唯一得到的是Optional(45 bytes)

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"}

使用Swift 4, String有一個名為init(data:encoding:) init(data:encoding:)具有以下聲明:

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

返回通過使用給定encoding將給定data轉換為Unicode字符而初始化的String


以下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"
 }
 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM