Back

Convert Velocity request parameters to JSON

  • Created: Apr 23, 2014
  • Author: Nathan I. Keiter
  • Title: Lead Network Applications Programmer

Description

Update to my previous submission.  I added an if block so it doesn't break if there are no request parameters.  Please replace this text with the description from my previous submission, then delete the old one.

Code

##################################################################################
##
## @title Convert Velocity request parameters to JSON
##
## @purpose Convert GET/POST vars into JSON Object using ONLY Velocity script
##
## @author nathan.keiter@gmail.com
##
## @notes This demo is optimized for readibility.  Output can be easily minified 
## by removing whitespace and subtracting 1 instead of 2 from $jsonString.length()
## I realize I could just write an OSGI ViewTool to do the conversion, but this 
## might be helpful to people who aren't comfortable doing that.
##
## @example URL
## www.example.com/test?field1=value1&field2=value2&field3=value3
## 
## @example output 
## { "field3" : "value3", "field2" : "value2", "field1" : "value1" } 
##
##################################################################################

#set( $jsonString = "" )
#set( $jsonObject = "{}" )

## Retrieve the request parameter keys
#foreach ( $key in $request.getParameterMap().keySet() )

	## Retrieve the request parameter value
	#set( $value = $request.getParameter( $key ) )

	## json escape the value String
	#set( $value = $esc.javascript( $value ) )

    ## jsonify the key->value property set
    #set( $jsonProperty = "\"" + $key + "\" : " + "\"" + $value + "\", " )

    ## Append to properties String
    #set( $jsonString = $jsonString + $jsonProperty )

#end

#if ( $jsonString.length() > 0 )

	## Trim off the last comma space from the properties String
	## Wrap properties String into JSON Object notation {}
	#set( $jsonStringLength = $jsonString.length() - 2 )
	#set( $jsonObject = "{ " + $jsonString.substring( 0, $jsonStringLength ) + " }" )

#end

## Output to page or pass into ViewTool as argument
$jsonObject