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

xwiki:XWiki.beldaz

Rating
Rate!
0 Votes
LicenseSimplified BSD License

Description

If you have a wiki page containing a script to generate JSON data, you need to take several steps to ensure it is correctly formatted.

  1. Set the content type with $response.setContentType('application/json')
  2. Avoid using the wiki formatting by using the wiki="false" option in your velocity and groovy scripts
  3. Render only 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'
  4. Prevent the output being rendered as html by using the outputSyntax=plain parameter option.

Example

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

{{velocity wiki="false"}}
$response.setContentType('application/json')
{
"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

JSON scripting support

XWiki includes a binding the jsontool Velocity tool.

{{velocity wiki="false"}}
#set($mylist = ['foo','bar'])
#set($mymap= {"things": $mylist})
$jsontool.serialize(${mymap})
{{/velocity}}

This can also be used from within Groovy by manually loading it:

{{groovy}}
def jsontool = new org.xwiki.velocity.tools.JSONTool()
print jsontool.serialize(['alice':2])
{{/groovy}}

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

Links

Prerequisites & Installation Instructions

Copy the code snippet to a page and save it.

Tags:
Created by beldaz on 2015/01/19 02:13
     

Get Connected