Output JSON
![]() | Example of how to generate JSON from a wiki page |
Type | Snippet |
Category | |
Developed by | xwiki:XWiki.beldaz |
Rating | |
License | Simplified BSD License |
Table of contents
Description
To output JSON, you need to ensure that:
- Nothing alters your output, including
- The icon transformation
- Wiki formatting -syntax interpretation
- HTML rendering
- 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):
#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:
#set($mylist = ['foo','bar'])
#set($mymap = {"things": $mylist})
$response.setContentType('application/json')
$response.writer.write($jsontool.serialize($mymap))
$xcontext.setFinished(true)
{{/velocity}}
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:
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
- The actions and outputSyntax option are explained in Standard URL Format
- Discussion leading to the outputSyntax parameter can be found on the mailing list