关于TP5会自动修改json字段类型问题

ThinkPHP 5.0.24

遇到的问题
当前端POST JSON数据到接口时, JSON中原本的int类型会被转化为string。

举个例子

// 前端传递的数据
{
	"id": 30,
    "name": "流程1",
    "description": "这里是流程1",
    "step": 1,
}
// 使用TP框架的获取方法
$this->request->post();

在这里插入图片描述
接口接收到的数据直接就转化为string类型了

分析与解决方法

通过查看think/Request源码,我们可以知道:在(当前情况下)调用post()时,$this->post等于解码后的 $content,这个 $content就是 file_get_contents(‘php://input’),即前端提交的数据,所以在这个阶段是没有问题的,问题就在最后的return $this->input()方法。

一看input()方法,其实答案就出来了,直接在post()中加个false就行了,$this->request->post(false);

// think/Request
public function post($name = '', $default = null, $filter = '')
{
     if (empty($this->post)) {
         $content = $this->input;
         if (empty($_POST) && false !== strpos($this->contentType(), 'application/json')) {
             $this->post = (array) json_decode($content, true);
         } else {
             $this->post = $_POST;
         }
     }
     if (is_array($name)) {
         $this->param       = [];
         $this->mergeParam  = false;
         return $this->post = array_merge($this->post, $name);
     }
     return $this->input($this->post, $name, $default, $filter);
}

public function input($data = [], $name = '', $default = null, $filter = '')
{
    if (false === $name) {
        // 获取原始数据
        return $data;
    }
    $name = (string) $name;
    if ('' != $name) {
        // 解析name
        if (strpos($name, '/')) {
            list($name, $type) = explode('/', $name);
        } else {
            $type = 's';
        }
        // 按.拆分成多维数组进行判断
        foreach (explode('.', $name) as $val) {
            if (isset($data[$val])) {
                $data = $data[$val];
            } else {
                // 无输入数据,返回默认值
                return $default;
            }
        }
        if (is_object($data)) {
            return $data;
        }
    }

    // 解析过滤器
    $filter = $this->getFilter($filter, $default);

    if (is_array($data)) {
        array_walk_recursive($data, [$this, 'filterValue'], $filter);
        reset($data);
    } else {
        $this->filterValue($data, $name, $filter);
    }

    if (isset($type) && $data !== $default) {
        // 强制类型转换
        $this->typeCast($data, $type);
    }
    return $data;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值