JSONDecoder and null response

I am having some issues decoding `null` responses from some REST APIs, using JSONDecoder. According to the spec, `null` is a valid JSON text, along with `true` and `false :


A JSON value MUST be an object, array, number, or string, or one of
  the following three literal names:

  false null true


Though when I use JSONDecoder to handle the response of a DELETE or a GET for non-existent values (both of which return a 200 HTTP status code with `null` in the body), I get the following error :


Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}))))


Seems that the default decode(type:data:) calls JSONSerialization.jsonObject(with: data) without the allowFragments reading option.


  do {
  topLevel = try JSONSerialization.jsonObject(with: data)
  } catch {
  throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not e
  }

So is there a way to use JSONDecoder with valid JSON data, such as `null`, `true` or `false` ?

If not, does anyone know if there is an existing BUG # (couldn't find it) ?


Thanks,

N.


NOTE : to avoid any confusion `null` is the entire content of the body response (not the value associated with a key).


HTTP/1.1 200
status: 200
server: nginx
date: Thu, 02 Aug 2018 21:53:27 GMT
content-type: application/json; charset=utf-8
content-length: 4
connection: keep-alive
access-control-allow-origin: *
cache-control: no-cache
strict-transport-security: max-age=31556926; includeSubDomains; preload

null

This is a known problem with JSONDecoder (bugs.swift.org/browse/SR-6163) — it currently requires an array or dictionary at the top level.

JSONDecoder and null response
 
 
Q