簡體   English   中英

如何在moodle webservices中以JSON的形式返回數據

[英]How to return data as JSON in moodle webservices

我正在moodle中創建一個網絡服務,並希望將我的std object 作為 JSON 返回,

public static function add_attendance_lti($attendanceObject)
    {
......
$lti_updated = [
            'id' => $insert_new_attendance,
            'code' => $statusCode,
            'message' => $message,
            'data' => json_encode($AttendanceLog)
        ];
        return $lti_updated;
  }

public static function add_attendance_lti_returns()
    {
        return new external_single_structure(
            array(
                'id' => new external_value(PARAM_RAW, 'New Attendance id'),
                'code' => new external_value(PARAM_INT, 'status code of response'),
                'message' => new external_value(PARAM_TEXT, 'message returned'),
                'data' => new external_value(PARAM_RAW, 'Return Value')
            )
        );
    }

在這里,我使用 json_encode() 將 $AttendanceLog std object 轉換為 JSON,但這會返回以下數據,

{
    "id": null,
    "code": 200,
    "message": "Attendance Record already exists",
    "data": "{\"sessionid\":\"18\",\"timetaken\":1643335205,\"studentid\":\"4\",\"takenby\":\"3\",\"statusset\":\"49,51,52,50\",\"statusid\":\"52\"}"
}

我如何在沒有 \" 的情況下返回正常的“數據” JSON object

您正在使用 json_encode 將 add_attendance_lti 中的字符串編碼為 json,生成的字符串將在add_attendance_lti_returns轉義 因此,這種削減編碼。

您可以嘗試將std object轉換為add_attendance_lti中的數組

public static function add_attendance_lti($attendanceObject)
    {
......
$lti_updated = [
            'id' => $insert_new_attendance,
            'code' => $statusCode,
            'message' => $message,
            'data' => json_decode(json_encode($AttendanceLog), true)
        ];
        return $lti_updated;
  }

(參見php stdClass to array

這樣,此方法將返回一個數組,另一端的鍵“數據”的 json 的值將是 json - 而不是轉義字符串。

傳遞 $AttendanceLog 變量,而不在數據鍵中使用 json_encode,然后像這樣 json_encode($lti_updated); 將 $lti_updated 轉換為 json_encode; 作為回報 return json_encode($lti_updated);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM