Search code examples
grailsservicecontrollerdataflow

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


I understand the general dictum to isolate business logic to service methods in Grails. All my previous Grails web services, have no inbound JSON, XML etc. Currently, I am required to take JSON payload, which contains {finish_time: 2020-05-12T18:19:00Z, start_time: 2020-05-14T18:19:00Z}, to use in my SQL. Running Grails 2.5.6. 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. I’m not versed in Grails well enough to waste ya’lls time showing what I’ve tried. I have not found any examples/explanations of service methods working on inbound https posted JSON/XML data from the controller. Thank You in advance, as to me this seems like a very fundamental task.


Solution

  • Pass the json data as an argument to a service method that handles this operation

    Controller action

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

    Service method

    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
    }