Over a million developers have joined DZone.

JSON.Net, the Groovy way

DZone's Guide to

JSON.Net, the Groovy way

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

On Ajaxian, the other day, I spotted an article about JSON.Net, a project aiming at simplifying the production and consumption of JSON data for the .Net world, and I wanted to contrast what I've read with what we are doing with Groovy and Grails. I rarely speak about the Microsoft world, but the latest features of C# 3 are very interesting and powerful, particularly the anonymous types, their closures (whatever they are called), and LINQ for querying relational or tree structured data.

For instance, here's how JSON.Net produces JSON content:

    JObject o = JObject.FromObject(new
channel = new
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories

Here, we can see the new anonymous type feature, with the new {} construct to easily create new data structure, without requiring the creation of classes or interfaces. And in the item element, we notice LINQ at work providing an SQL like notation to select the posts ordered by title.

In Groovy and Grails land, we are reusing the map notation to create JSON content, that we then coerce to JSON using the as operator:

    import grails.converters.JSON

def data = [
channel: [
title: "James Newton-King",
link: "http://james.newtonking.com",
description: "James Newton-King's blog.",
posts.sort { it.title }.collect {
title: it.title,
description: it.description,
link: it.link,
category: it.categories

// then, if you want to render this structure as JSON inside a Grails controller:
render data as JSON

Unlike LINQ with its SQL-like notation, Groovy favors a more functional approach, using the sort() and collect() taking closures to do the filtering and aggregation. These methods are added by the Groovy Development Kit to the usual Java collection classes.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}