如何将 HttpServletRequest JSON 入站数据从控制器传递到服务方法

How to pass HttpServletRequest JSON inbound data from controller to service method

我理解将业务逻辑与 Grails 中的服务方法隔离开来的一般格言。我以前所有的 Grails Web 服务,都没有入站 JSON、XML 等。目前,我需要使用 JSON 有效载荷,其中包含 {finish_time: 2020-05- 12T18:19:00Z, start_time: 2020-05-14T18:19:00Z},用于我的 SQL。 运行 圣杯 2.5.6。不幸的是,我不知道服务方法如何访问入站 JSON 有效负载数据。这一定很常见,但我不理解从控制器到服务方法的数据 pass/access。我对 Grails 不够精通,无法浪费你们的时间来展示我的尝试。我没有发现任何 examples/explanations 的服务方法处理入站 https 从控制器发布 JSON/XML 数据。提前谢谢你,对我来说这似乎是一项非常基本的任务。

Unfortunately, I have no idea how service methods, can access the inbound JSON payload data. This has to be common, but I am not understanding data pass/access from controller to service methods.

有很多方法可以访问服务中的 JSON 有效负载数据,但没有太多好的理由想要这样做。通常人们会在控制器级别做这种事情。您提到了“...将业务逻辑与 Grails 中的服务方法隔离开来的一般格言”,但这不是业务逻辑。在 Grails 控制器中处理请求正文等 Web 层细节是一件非常合理的事情。

你可以拥有这样的控制器...

class SomeController {

    SomeService someService

    def someAction(Widget w) {
        someService.doSomething w
    }
}

这样,如果您 POST JSON 到 someAction,所有 JSON 阅读都将为您完成,而 Widget 将是用 JSON 的内容初始化。

希望对您有所帮助。

编辑

I need to see how to set up the Service too.

// grails-app/services/demo/SomeService.groovy
package demo

class SomeService {
    void doSomething(Widget w) {
        // Do whatever you need to do with 
        // the information in the Widget...
    }
}

将 json 数据作为参数传递给处理此操作的服务方法

控制器动作

def actionName() {
    def json = '{"finish_time": "2020-05-12T18:19:00Z", "start_time": "2020-05-14T18:19:00Z"}'
    serviceInstance.methodName(json)
}

服务方式

def methodName(json) {
    def jsonSlurper = new JsonSlurper()
    def data = jsonSlurper.parseText(json) // here data is a Groovy data structures in this case a Map

    // ... sql logic
}