Groovier JSON
Andres Almiray June 1st, 2007
It’s time for a batch of updates on what’s been going on the Groovy side of Json-lib.
- Because JSONObject and JSONArray now implement java.util.Map and java.util.List you can use them as such in Groovy.
- JSONObject and JSONArray also implement java.util.Comparable, making it very easy to use the comparison operators (even the spaceship operator). I’ve found a caveat so far, because JSONArray is also a List, the interpreter will throw an Exception stating that it can compare the two values, but you can use
compareTo()(as in Java) for the time being. - The leftshift ( << ) operator is supported by JSONObject, the accepted values are Map and List and it works as a shorthand for
element(), it follows these rules:- If the shifted arg is a Map, it will call
putAll()on the object. - If the shifted arg is a List and its size == 2, the first element will be the key, and the second will be the value.
- If the shifted arg is a List and its size > 2, the first element will be the key, the arg will be shifted by 1 and passed as the value (will create a JSONArray because it is a List).
- Any other type will be discarded, the object will not be affected nor an exception will be thrown.
- If the shifted arg is a Map, it will call
- The JsonGrovyBuilder is finished, I used Grail’s BeansBuilder as a reference instead of going with the traditional way of extending BuilderSupport, this approach allows for the following code to be transformed into the same JSON:
- def books1 = builder.books {
- book = [title: “The Definitive Guide to Grails”, author: “Graeme Rocher”]
- book = [title: “The Definitive Guide to Grails”, author: “Graeme Rocher”]
- }
- def books2 = builder.books {
- book = new Book(title: “The Definitive Guide to Grails”,
- author: “Graeme Rocher”)
- book = new Book(title: “The Definitive Guide to Grails”,
- author: “Graeme Rocher”)
- }
- def books3 = builder.books {
- book = {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- book = {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- }
- def books4 = builder.books {
- book {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- book {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- }
- def books5 = builder.books {
- 2.times {
- book = {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- }
- }
- def books6 = builder.books {
- 2.times {
- book {
- title = “The Definitive Guide to Grails”
- author= “Graeme Rocher”
- }
- }
- }
- /*
- all 6 books variables output the same JSON
- {”books”: {
- “book”: [{
- “title”: “The Definitive Guide to Grails”,
- “author”: “Graeme Rocher”
- },{
- “title”: “The Definitive Guide to Grails”,
- “author”: “Graeme Rocher”
- }]
- }
- }
- */
Tags: Andres Almiray
About
Leave a Comment