0

I have encoded a Codable object:

let encodedData = try JSONEncoder().encode(someObject)

And I print the JSON by doing the following (I know its not safe, I'm just testing):

let json = try! JSONSerialization.jsonObject(with: encodedData)
print("JSON:  \(json)")

My JSON has lots of spaces. I want a way to remove these spaces, to save space on the encoded String. You can tell that it looks quite different from a normal JSON due to these spaces.

JSON (part of it):

JSON format

How can I reduce the spaces to reduce the bytes this takes up?

George
  • 25,988
  • 10
  • 79
  • 133
  • 1
    That does not print the JSON. You convert the JSON data back to a dictionary and what you see is the description of an NSDictionary. – To see the JSON, use `print(String(data: encodedData, encoding: .utf8)!)` – Martin R Feb 01 '20 at 21:37
  • @MartinR If you add it, I will accept it as an answer. – George Feb 01 '20 at 22:22

1 Answers1

0

As @Martin R pointed out, I was not printing the JSON properly. It should have instead been:

let jsonString = String(data: encodedData, encoding: .utf8)!
print(jsonString)

The result looks like so:

{"type":1,"modifiers":[],"parameters":{ ...

This printed data can then be decoded in the future like so:

let data = Data(jsonString.utf8)
let someResult = try JSONDecoder().decode(SomeType.self, from: data)
George
  • 25,988
  • 10
  • 79
  • 133