Output JSON

Last modified by Raphaël Jakse on 2025/02/12 12:25

cogExample of how to generate JSON from a wiki page
TypeSnippet
Category
Developed by

xwiki:XWiki.beldaz

Rating
0 Votes
LicenseSimplified BSD License

Description

To output JSON, you need to ensure that:

  • Nothing alters your output, including
  • You only render the specified content (and not all the menus, etc.) by using the plain.vm template - you can do this automatically by using the 'get' action or explicitly setting the template with 'xpage=plain'
  • the correct HTTP content-type is sent.

To avoid any altering including icon transformation, you need to write to the Response object directly.

In Velocity

In velocity, the #jsonResponse macro does all the work for you. Set the output=false parameter to avoid unnecessary parsing.

Consider the following page (assume it is page JsonHello in space JsonDemo):

{{velocity output="false"}}
  #jsonResponse({
    "greeting" : "Hello",
    "location": "World"
  })
{{/velocity}}

This should then be accessed via path /xwiki/bin/get/JsonDemo/JsonHello?outputSyntax=plain or /xwiki/bin/get/JsonDemo/JsonHello?xpage=plain&outputSyntax=plain

If you already have a JSON string / need more control, you can do something like this:

{{velocity wiki="false"}}
  #set($mylist = ['foo','bar'])
  #set($mymap = {"things": $mylist})
  $response.setContentType('application/json')
  $response.writer.write($jsontool.serialize($mymap))
  $xcontext.setFinished(true)
{{/velocity}}

Make sure you disable wiki formatting with the wiki="false" parameter of the Velocity macro!

The $xcontext.setFinished(true) call ensures nothing will be written after the JSON data.

In Groovy

There's nothing like #jsonResponse in Groovy, so you will need to do it manually.

You can use JsonSlurper, or even manually import jsontool:

{{groovy}}
def jsontool = new org.xwiki.velocity.tools.JSONTool()
response.setContentType('application/json')
response.getWriter().write(jsontool.serialize(['alice': 2]))
xcontext.setFinished(true)
{{/groovy}}

Alternatively you can use the standard JSON libraries available to Groovy.

Links

Get Connected