首页 > 解决方案 > 更改 JSON-RPC 响应

问题描述

我正在使用 ODOO 11.0 如何在没有 JSON-RPC 附加参数的情况下返回简单的 JSON 对象

这是我的 odoo 控制器代码:

@http.route('/userappoint/webhook_test/',type='json', auth='public',method=['POST'], csrf=False,website=True)
def webhook_test(self,**kw):

    response = {
        'speech'        : 'hello my name is shubham',
        'displayText'   : 'hello testing',
        'source'        : 'webhook'
    }
    return response

我得到了这个结果:

{
"result": {
             "displayText": "hello testing",
             "source": "webhook",
             "speech": "hello my name is shubham"
          },
"id": "6eaced3e-6b0d-4518-9710-de91eaf16dd9",
"jsonrpc": "2.0"
}

但我需要这个:

{
"speech": "hello my name is shubham",
"displayText": "hello testing",
"source": "webhook" 
}

有什么帮助可以为我指明正确的方向吗?谢谢

标签: pythonjson-rpcodoo-11

解决方案


在初始化控制器类之前,将以下代码放在任何控制器中

from odoo import http
from odoo.http import request, Response, JsonRequest
from odoo.tools import date_utils

class JsonRequestNew(JsonRequest):

    def _json_response(self, result=None, error=None):

        # response = {
        #    'jsonrpc': '2.0',
        #    'id': self.jsonrequest.get('id')
        #    }
        # if error is not None:
        #    response['error'] = error
        # if result is not None:
        #    response['result'] = result

        responseData = super(JsonRequestNew, self)._json_response(result=result,error=error)

        response = {}
        if error is not None:
            response = error
        if result is not None:
            response = result

        mime = 'application/json'
        body = json.dumps(response, default=date_utils.json_default)

        return Response(
            body, status=error and error.pop('http_status', 200) or 200,
            headers=[('Content-Type', mime), ('Content-Length', len(body))]
        )

class RootNew(http.Root):

    def get_request(self, httprequest):
        
        # deduce type of request

        jsonResponse = super(RootNew, self).get_request(httprequest=httprequest)

        if httprequest.mimetype in ("application/json", "application/json-rpc"):
            return JsonRequestNew(httprequest)
        else:
            return jsonResponse

http.root = RootNew()

class MyController(http.Controller):

推荐阅读