Groovy – Producing JSON using Groovlet and JSONObject
All right I admit I like groovy, because it’s gives you taste of best of both worlds – all the dynamism of Python and Ruby and still be close to Java.
I was trying to create simple JSON output using Groovlets and JSONObject and this is what I came up with.
In order to use Groovlets use the this link to set it up in your favorite IDE.
And then
-
Create index.groovy in WEB Folder.
-
Download the source code from json.org/java site
-
put in your src folder of web project.
-
In your index.groovy put in this code
Here’s the code
import org.json.*;
import com.ranjan.*;
/***************************************************
*
*
Setting up response content type is
important
*
and in best practice.
****************************************************/
response.setContentType("application/json");
def fromMap =
[name:"Frederic Jean",age:32]
as JSONObject
def fromList =
["English","French","Spanish"]
as JSONArray
def newMap =
[
world:[
countries:[
india:[
cities:["delhi", "bombay"]
],
america:[
states:["new york", "chicago"]
],
japan:[
states:["tokyo","some great japanese city"]
]
]
]
]
as JSONObject
// this is what does the trick
println newMap
The result...
