public static function writeJSON($obj, $buf = null)
    {
        $output = json_encode($obj);

        if ($output === false && json_last_error() === JSON_ERROR_UTF8)
        {
            $obj_fixed = Encoding::fixUTF8($obj);
            $output = json_encode($obj_fixed);
            if ($output === false && json_last_error() === JSON_ERROR_UTF8)
            {
                // @codeCoverageIgnoreStart
                // The input has to be extremely weird to trigger this, so
                // in practice it shouldn't happen.  
                $rep = WF::str($obj); 
                throw new IOException("Invalid encoding: " . $rep); 
                // @codeCoverageIgnoreEnd
            }
        }

        if (is_resource($buf))
        {
            fwrite($buf, $output);
            return "";
        }

        return $output;
    }