JSON Body Escaping

19.05.2020
1 min

I think many iOS developers have worked with escaping URL. But can you instantly answer does JSON escapes when it sending to body? In my work, I faced the fact that by default the JSON body of the query is escaped when using the standard JSONEncoder. So you can ask what is wrong with this?

bug.svg The problem

Just imagine that you send an address: Tram Lane 3/4. What did we get in body? This: Tram Lane 3\/4. And then an unhappy manager will decode this address manually (no one manager was affected during development).

idea.svg Solution

The good news is we can fix it easily! JSONEncoder has the withoutEscapingSlashes property.

The bad news is that only for iOS 13. Otherwise, you will have to do it manually. Here is a short example of what this might look like:

struct WithoutEscapingSlashesEncoder {
private enum EncoderError: InternalError {
case dataToUTF8
case utf8ToData
}
func encode<T: Encodable>(_ object: T) throws -> Data {
let jsonEncoder = JSONEncoder()
if #available(iOS 13, *) {
jsonEncoder.outputFormatting = .withoutEscapingSlashes
return try jsonEncoder.encode(object)
} else {
let data = try jsonEncoder.encode(object)
guard let string = String(data: data, encoding: .utf8)
else { throw EncoderError.dataToUTF8 }
let fixedString = string.replacingOccurrences(of: "\\/", with: "/")
guard let fixedData = fixedString.data(using: .utf8)
else { throw EncoderError.utf8ToData }
return fixedData
}
}
}


💬 Please, leave some feedback in Twitter post: