ßeta perpetua

El blog personal de Juan Manuel Barroso

Useful Tips: Groovy JSON Pretty Print

4 Comments »

La representación de objetos usando JSON es muy sencilla pero si deseamos enviarla a un log, o imprimirla para depurar, más nos vale que esté correctamente  formateada.

Groovy provee una clase que nos permite hacerlo de manera indolora. La clase en cuestión es groovy.json.JsonOutput y el método es prettyPrint.

def jsonWithoutFormat = """{"firstName":"John","lastName":"Smith",
                    "age":25,"address":{"streetAddress":"212ndStreet",
                    "city":"NewYork","state":"NY","postalCode":"10021"},
                     "phoneNumber":[{"type":"home","number":"212555-1234"},
                     {"type":"fax","number":"646555-4567"}]}"""
 
def jsonFormatted = groovy.json.JsonOutput.prettyPrint(jsonWithoutFormat)

El resultado de prettyPrint:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "212ndStreet",
        "city": "NewYork",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212555-1234"
        },
        {
            "type": "fax",
            "number": "646555-4567"
        }
    ]
}

Al final hemos obtenido una cadena que representa un JSON correctamente formateado.

4 Responses

Fell out of bed feeling down. This has breghtenid my day!

  • The eyes, can’t get away from the eyes…OK, now after the second viewing. The smile! Reminds me of that guy one one of those CSI series. The beautiful coffee& cream skin, liquid eyes and a smile that takes me to heaven. I don’t watch TV, but have caught glimpses of this guy (in which I’m speaking) from time to time at my aunt’s house. A truly striking male. BTW, I wish they would have cracked that fatty open instead of trying to drown it! OH, that smile!

  • ¡Qué chafón :-D ! Tantos años acostumbrado a usar man, y ahora no me acuerdo de hacerlo (precisamente porque las formulas de homebrew no te suelen instalar las páginas del manual )… lo busqué en Google así en plan rápido pero no di con ello, ¡shame on me !(¡Gracias :D !)

  • 13 décembre 2010Mouais, mouais, mouais…C’est toujours pareil : une marque réellement intéressante ne devrait théoriquement pas avoir besoin de distribuer des cadeaux faramineux pour se faire connaître.Si tu mets bout à bout les iPad, les Louboutin, la bouffe, la picole et les capotes pour les soirées bloggeuses, ça aurait pu payer l’impression d’un n°2.Bon courage pour la suite, rdv sur votre fanpage. Cordialement.

  • Leave a Reply to excelsior.com.mx