普通网友 2015-06-02 07:29
浏览 195
已采纳

json_decode和json_encode长整数而不会丢失数据

As noted in the PHP documentation, when json_decodeing a data structure containing long integers, they'll be converted to floats. The workaround is to use JSON_BIGINT_AS_STRING, which preserves them as strings instead. When json_encodeing such values, JSON_NUMERIC_CHECK will encode those numbers back into large integers:

$json  = '{"foo":283675428357628352}';
$obj   = json_decode($json, false, JSON_BIGINT_AS_STRING);
$json2 = json_encode($obj, JSON_NUMERIC_CHECK);
var_dump($json === $json2); // true

Using this method for a correct roundtrip of the data is prone to errors. If a property contains '123', a numeric string which should stay a string, it will be encoded to an integer.

I want to get an object from the server, modify one property and than put the entire data structure back. I need to preserve the original types. I don't want to maintain properties other than the one I'm manipulating.

Is there any real workaround for this? PHP does not have any issues with big ints anymore, but the json_decode routine seems to be outdated.

  • 写回答

2条回答 默认 最新

  • douju9272 2015-06-02 08:03
    关注

    As long as your PHP version can actually handle large integers, meaning if you're running a 64-bit version of PHP (on something other than Windows), json_decode has no problem with it:

    $json  = '{"foo":9223372036854775807}';
    $obj   = json_decode($json);
    $json2 = json_encode($obj);
    
    var_dump(PHP_INT_MAX, $obj, $json2);
    
    int(9223372036854775807)
    object(stdClass)#1 (1) {
      ["foo"]=>
      int(9223372036854775807)
    }
    string(27) "{"foo":9223372036854775807}"
    

    If the integer values you need to handle do exceed PHP's PHP_INT_MAX, you simply cannot represent them in PHP native types. So there's no way around the conundrum you have; you cannot use native types to track the correct type, and you cannot substitute other types (e.g. strings instead of integers), because that's ambiguous when encoding back to JSON.

    In this case you will have to invent your own mechanism of tracking the correct types for each property and handle such serialisation with a custom encoder/decoder. For example, you'd need to write a custom JSON decoder which can decode to a custom class like new JsonInteger('9223372036854775808'), and your custom encoder would recognise this type and encode it to a JSON 9223372036854775808 value.

    There's no such thing built into PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算