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

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}