Recherche…


Analyser une chaîne 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]

Analyser un fichier 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)

Ecrivez un json à la chaîne

import groovy.json.JsonOutput;

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

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

En plus des cartes, des listes et des primitives, groovy.json.JsonOutput prend également en charge une sérialisation de POJO :

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"}]'

Jolie-imprimer une chaîne 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
    ]
}'''

Ecrit un json dans un fichier

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
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow