Getting error information when parsing JSON response from XPRIM_HttpRequest

This forum allows developers to post programming tips and coding techniques that may be useful to other Visual LANSA developers. The information contained in this forum has not been validated by LANSA and, as such, LANSA cannot guarantee the accuracy of the information.
Post Reply
tsupartono
Posts: 22
Joined: Wed Jan 25, 2017 11:12 am

Getting error information when parsing JSON response from XPRIM_HttpRequest

Post by tsupartono » Thu Aug 24, 2017 8:09 pm

When you make a web service invocation using XPRIM_HttpRequest and you are expecting to receive a JSON response, don't assume that you are always going to get a valid JSON response.

Some examples of situations where the server may not return a valid JSON:
  • When the server thinks your request is not a valid request, it may give back an HTTP status code 400 without providing more information (blank body).
  • The server for some reason returns a different content type (for example, text/plain), which is indicated in the 'Content-Type' response header.
  • Or, the server just simply returns an invalid JSON! (unlikely but not unheard of).
It's useful to check that the response returns an OK HTTP status code (2xx), the correct content type, and proper JSON.

To check if the returned HTTP status code indicates a successful operation, use the following

Code: Select all

#Request.Response.IsSuccessHttpStatusCode
To check if the response content type is 'application/json':

Code: Select all

#Request.Response.ContentInfo.MediaType = 'application/json'
To check that the JSON parsed OK, use the Status parameter when invoking AsJson method:

Code: Select all

Define_Com Class(#XPRIM_Json) Name(#ResponseJson) Reference(*DYNAMIC)
Define_Com Class(#XPRIM_HttpResponseReadContentStatus) Name(#Status) Reference(*DYNAMIC)

#Request.Response.AsJson Result(#ResponseJson) Status(#Status)
You can then interrogate the #Status object like so:

Code: Select all

If (*Not #Status.OK)
   #Message := #Status.ErrorMessage 
EndIf
If the JSON is not a valid one, the error message will show something like this:

Code: Select all

'JSON parsing error at offset 0: Expect either an object or array at root'

Post Reply