Groovy Map to Json String converter

I use Groovy a lot. It’s simple and easy to use, runs on JVM and saves me from Java verbosity. I also like the fact that it’s dynamic.

I use it with a simple Servlet to return data to JavaScript AJAX requests. I like to keep the server side very simple, so I don’t create a lot of POJOs and I’m using HashMaps instead. Groovy has few convenient methods that makes it easy to work with Maps.

I do convert the maps into JSON when returning results to a browser. I don’t use anything fancy, just a couple lines of Groovy code to do that.

With this code there is quite a bit of assumptions though:

  • it will only work for Map
  • it assumes Strings are used as Map Keys
  • it will convert Maps, Lists and Objects
  • when it meets Object it will call .toString() on it to get it’s value
  • it will try to format it with tabs and new lines a bit, so it’s more pleasant for the eye and human readable

Hope it would be useful for you. Greg

2 thoughts on “Groovy Map to Json String converter

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s