douji9518 2017-06-06 07:15
浏览 188

PHP中的JSON编码无符号64位整数

I know PHP does not support unsigned 64 bit integers.

However I simply need to read unsigned 64 bit integer values from a MySQL table via PDO query, and pass them through to clients (without performing any calculation or comparison); the PHP page is publishing a very simple REST interface to clients and should output the query result as JSON data only.

Right now the PDO query returns untouched integers as long as they are 63bit wide (no sign), but when the original value in the table has the 64th bit set, the PDO driver converts it to a string (I have set PDO::ATTR_STRINGIFY_FETCHES attribute to false, since I want types to be preserved as much as possible).

When I call the json_encode() function, the related fields get the same treatment: they become strings when they exceed 63 bit width.

I do not want to leave them as strings in json output, since it would require "breaking" changes in client code to have them handling json-string to ulong conversion upon decoding.

Is there a way to customize json_encode behavior somehow to output them as "UInt64" ?

I've taken a look at JsonSerializable but it seems it cannot solve my issue.

  • 写回答

1条回答 默认 最新

  • duanbei8904 2017-06-06 16:12
    关注

    I found a workaround to the problem, not exactly "elegant", but practical (and it works).

    I've included in my project a custom pure-PHP json encoding library found on GitHub here.

    I've declared this interface:

    interface JSONSerializer
    {
        public function toJSON();
    }
    

    I've implemented the interface in this simple class:

    class UInt64Raw implements JSONSerializer {
    
        private $value;
    
        public function __construct($number) {
            $this->value = $number;
        }
    
        public function getValue() { return $this->value; }
    
    
        public function toJSON() {
            if (is_null($this->value)) return "null";
            if ($this->value) return (string)$this->value;
            return "0";
        }
    
    } 
    

    I've changed a little bit the default behavior of the JSON encoder library in order to invoke the interface method whenever the object to be encoded is implementing that interface.

    I can then retrieve unsigned 64 bit integers as strings from PDO, wrap them inside a UInt64Raw object instance and eventually pass them unquoted (as numbers) through custom JSON encoding.

    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)