Buscar..


Analizar una cadena json

import groovy.json.JsonSlurper;

def jsonSlurper = new JsonSlurper()
def obj = jsonSlurper.parseText('{ "foo": "bar", "baz": [1] }')

assert obj.foo == 'bar'
assert obj.baz == [1]

Analizar un archivo json

import groovy.json.JsonSlurper;

def jsonSlurper = new JsonSlurper()

File fl = new File('/path/to/fils.json')

// parse(File file) method is available since 2.2.0
def obj = jsonSlurper.parse(fl)

// for versions < 2.2.0 it's possible to use
def old = jsonSlurper.parse(fl.text)

Escribe un json a la cuerda

import groovy.json.JsonOutput;

def json = JsonOutput.toJson([foo: 'bar', baz: [1]])

assert json == '{"foo":"bar","baz":[1]}'

Además de los mapas, listas y primitivas, groovy.json.JsonOutput también admite una groovy.json.JsonOutput POJOs :

import groovy.json.JsonOutput; 
 
class Tree { 
    def name
    def type
}

Tree willow = new Tree(name:'Willow',type:'Deciduous')
Tree olive = new Tree(name:'Olive',type:'Evergreen')

assert JsonOutput.toJson(willow) == '{"type":"Deciduous","name":"Willow"}'
assert JsonOutput.toJson([willow,olive]) == '[{"type":"Deciduous","name":"Willow"},{"type":"Evergreen","name":"Olive"}]'

Bonita impresión de una cadena json

import groovy.json.JsonOutput;

def json = JsonOutput.toJson([foo: 'bar', baz: [1]])

assert json == '{"foo":"bar","baz":[1]}'

def pretty = JsonOutput.prettyPrint(json)

assert pretty == '''{
    "foo": "bar",
    "baz": [
        1
    ]
}'''

Escribe un json a un archivo

import groovy.json.JsonOutput;

def json = JsonOutput.toJson([foo: 'bar', baz: [1]])
 
new File("/tmp/output.json").write(json)


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow