18
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?

If I use print(json) the only thing I get is Optional(45 bytes)

mfaani
  • 33,269
  • 19
  • 164
  • 293
Amir
  • 523
  • 1
  • 5
  • 24

2 Answers2

36

The encode() method returns Data containing the JSON representation in UTF-8 encoding. 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"}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • thanks for your answer , can you tell me what's the difference between `JSONEncoder` and `JSSONSerilization` ? – Amir Jul 10 '17 at 18:47
  • @Amir: JSONEncoder/JSONDecoder are new in Swift 4 and – roughly speaking – allow the encoding/decoding of custom data structures. See https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md for the details. See also the "Swift 4" part in https://stackoverflow.com/documentation/swift/223/reading-writing-json#t=201707101855392281446. – Martin R Jul 10 '17 at 18:54
  • Nice one! Thx :) – devjme Dec 28 '21 at 19:19
5

With Swift 4, String has a initializer called init(data:encoding:). init(data:encoding:) has the following declaration:

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

Returns a String initialized by converting given data into Unicode characters using a given encoding.


The following Playground snippets show how to use String init(data:encoding:) initializer in order to print a JSON data content:

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:

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"
 }
 */
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218