Class wwJsonService

This class is a self contained JSON method handler. It takes a REQUEST object as input and based on the request input routes the request to a method that is called optionally with parameters specified as part of the request.

You can also use a pre-made process classes called wwRestProcess that internally implements sets up and calls wwJsonService, so any methods are automatically mapped to JSON endpoints.

The class is fully self contained and handles the entire process of parsing parameters, calling the method, handling errors, and returning a JSON result string. All results including code errors always return a JSON result.

The class accepts Web input in 3 different ways:

  • POST parameters using ajaxMethodCallback() or the wwAjaxMethodCallback control
    This is the preferred way to call the service as it lets you basically call any method with any signature passing in multiple parameters. Parameters are expected to be JSON encoded. Use either the AjaxMethodCallback class or ajaxCallMethod() function in ww.jquery.js. Both of these are practically one liners. Content Type Expected: application/x-urlencoded Post Variables expected: CallbackMethod,CallbackParmCount,Parm1,Parm2..ParmN

  • POST a JSON value or object
    This mechanism allows you to effectively pass a single JSON encoded value/object to a method. The method called should take a single value/object parameter. Although a single parameter seems very limiting remember that you can easily encode multiple values into a wrapper object ( { myParm1: value, myParm2: value } ). The server method should be able to pick up those child objects and values as needed. Content Type Expected: Content-Type set to application/x-javascript or application/json Querystring Value expected: Method

  • No PostData or No CallbackMethod POST value
    Allows you to call the method and pass no data to it directly. You can still send POST data, but that data is not parsed or set in anyway. The method called then needs to pick out any 'parameters' or direction based on POST or QueryString data the request provides. Querystring Value expected: Method

  • JSONP Support
    You can also make JSONP callbacks by specifying a callback= querystring parameter to specify the callback method fired on the client by a JSONP capable client. JSONP repsonses simply wrap the resulting JSON data into a function call with the name of the callback query string value.

This class allows calling a method and returning JSON data from the result either using the client AjaxMethodCallback class which uses POST parameters, or by passing a single JSON parameter from the client with content-type of application/x-javascript.

This class can be implemented as a plain Process method in Web Connection with very little code. This class handles all aspects of request parsing and output generation and acts as a proxy to call a method on an object which means it can route incoming requests to any method.

Custom
  wwJsonService

Remarks

Called service methods have two PRIVATE variables passed into them:

  • JsonService
  • Serializer

Using these references you can control the wwJsonService and wwJsonSerializer instances and perform tasks like override the JsonService.IsRawResponse to control output generation, or override the Serializer.cPropertyNameOverrides for proper cased values.

Class Members

MemberDescription

CallMethod

Generic call that is passed through and executes the remote method based on the information contained in the wwRequest object passed as input. The method is processed and the result returned as a JSON string. An error produces a JSON error object.

o.CallMethod(Request, TargetObject)

OnError

Event method that is called when an error occurs during processing. The exception is passed.

o.OnError(loException)

ReturnExceptionObject

Returns an JSON error respsonse that contains an object in the format of:

o.ReturnExceptionObject(lcMessage)

AllowedMethods

Optional comma delimited list of methods that are to callable on the the target object.

ErrorMessage

Last error message that is set if an error occurs during the CallMethod call. Use to pick up error messages after a call to CallMethod.

ErrorOccurred

Returns if an error occurred in the process of the JSON method call (CallMethod()).

IsDebugMode

Flag that if .T. causes errors to stop rather than get handled by the TRY/CATCH handler for error reporting.

IsRawResponse

Allows the called method to specify that the result from the method should not be serialized. Used by wwRestService to not try set a content type or serialize and send out the result.

LastException

Contains the last exception that occurred after a call to CallMethod.

Example

************************************************************************
*  JsonCallbacks
****************************************
***  Function: Demonstrates how to create a generic wwJSONService
***            end point in a process class.
***            This method uses a separate object to handle the
***            actual method calls but you could also use THIS
***            as the target object to directly execute Process
***            Methods.
***
***            ajaxCallMethod("JsonCallbacks.wwd?Method=MyMethod",["parm1",10,new Date()],onSuccess,onError)
***            ajaxJson("JSONCallbacks.wwd?Method=MyMethod",null,onSuccess,onError);
***      Pass: 
***    Return:
************************************************************************
FUNCTION JsonCallbacks()

lcMethod = Request.QueryString("Method")

*** You don't have to create a new object - you can also use THIS
*** But using a separate object ensures you only expose methods
*** you care to expose rather than Process methods
lotarget= CREATEOBJECT("AjaxCallbacks")

*** Instantiate the Json Service
loService = CREATEOBJECT("wwJsonService")

*** Response is ALWAYS JSON unless there's a hard server error 
Response.ContentType = "application/json"

*** Simply call the specified method - 
*** The service will pull out method parameters from REQUEST
*** Note the service will handle errors internally and return
*** a JSON error object 
lcJSON = loService.CallMethod(Request,loTarget,lcMethod)

*** Write out the result from CallMethod which returns the JSON for the method
*** or a JSON Error object if the call failed
Response.Write( lcJSON )
Response.End()

RETURN
ENDFUNC
*   JsonCallbacks

Requirements

Assembly: wwjsonserializer.prg

See also:

ajaxJson | ajaxCallMethod | Class wwJsonService | Class wwJsonSerialize | How to run JSON Ajax Requests without the Web Control Framework (deprecated) |

© West Wind Technologies, 1996-2024 • Updated: 10/28/17
Comment or report problem with topic