0

I have been trying to get JSONEncoder's dataEncodingStrategy work.

I need to get my http body data without escaped on API requests and there is this withoutEscapingSlashes: JSONEncoder.OutputFormatting of JSONEncoder but unfortunately this is only for iOS >= 13 whereas my app supports iOS >= 11.

This is what I have at the moment:

let encoder = JSONEncoder()
if #available(iOS 13, *) {
   encoder.outputFormatting = .withoutEscapingSlashes
} else {
   // Fallback to earlier versions here!
   // Looking for a workaround and I believe "dataEncodingStrategy" is what I am looking for.
}
try encoder.encode(data)

Here is a simple example from Playground for test purpose to show you what I wrote.

JSONEncoder.DataEncodingStrategy.custom (that is var strategy) is never called.

import Foundation

struct Model: Encodable {
    let key: String = "key goes here..."
}

var strategy: JSONEncoder.DataEncodingStrategy = .custom({ (data, encoder) in
    print("CALLED!") // This is never printed.
    if var string = String(data: data, encoding: .utf8) {
        string = string.replacingOccurrences(of: "key", with: "REPLACED")
        var container = encoder.singleValueContainer()
        let data = string.data(using: .utf8)
        try container.encode(data)
    }
})

let encoder = JSONEncoder()
encoder.dataEncodingStrategy = strategy

let m = Model()
let d = try! encoder.encode(m)
let str = String(data: d, encoding: .utf8)
print(str)

dataEncodingStrategy is always dismissed no matter what. It is never called. It is not deprecated or something. Does anybody know what is going on here?

Although this question is specific to JSONEncoder's dataEncodingStrategy, any other approach for keeping http body data without escaped for iOS < 13 would be helpful as well.

JustWork
  • 1,944
  • 3
  • 22
  • 34
  • `dataEncodingStrategy` – as the name implies – is how to encode values declared as `Data` . It has nothing to do with output formatting. – vadian Apr 08 '20 at 18:10

1 Answers1

1

dataEncodingStrategy is specifically for encoding values of type Data, not types like String that are natively supported.

Unfortunately, your only option to my knowledge for iOS < 13 is to basically do what you were trying to do in your encoding strategy closure — use .replacingOccurrences(of: "\\/", with: "/") on the encoded JSON string.

Brock Batsell
  • 5,786
  • 1
  • 25
  • 27