Webservice return array as JSON

Webservice return array as JSON

by Lloyd Thomas -
Number of replies: 2

I am trying to work with the recommeded parameters for providing a webservice for my plugin but I am a little stuck when I try to return a multi-dimensional array as JSON.

The function to validate outputs does not seem to cater for arrays regardless of which parameter (PARAM_RAW) I try to use.

public static function list_updated_returns() {
        return new external_single_structure(
            array(
                'result' => new external_value(PARAM_RAW, 'result: array of updated simplefeedback questionnaires'),
                'code' => new external_value(PARAM_INT, 'code: error code'),
                'warnings' => new external_warnings()
            )
        );
    }

For now I have to circumvent this by doing the following which I am happy to continue with, but I would like clarification if there is a Moodle way of doing this.

public static function list_updated($prevtime){
....... //generate $list_course_array array
......
......    
if(!empty($list_course_array)){          
            $result['result'] = $list_course_array;
            $result['code'] = '200';
            header('Content-Type: application/json');
            print json_encode($result);
            die();
        }
return $result;
}



Average of ratings: -
In reply to Lloyd Thomas

Re: Webservice return array as JSON

by Sam Chaffee -
Picture of Core developers

The problem you're running into is that Moodle wants you to define that array in the *_returns() method. I would take a look at a core example to see how it is done; course/externallib.php has some good examples.

Once you've defined the *_returns() method the way Moodle expects then you can pass moodlewsrestformat=json as a parameter on you web service call and Moodle will send back JSON.