Поиск…


Разбор строки 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]

Разберите файл 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)

Напишите json для строки

import groovy.json.JsonOutput;

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

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

В дополнение к картам, спискам и примитивам groovy.json.JsonOutput также поддерживает groovy.json.JsonOutput 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"}]'

Довольно печатать строку 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
    ]
}'''

Напишите json в файл

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
Лицензировано согласно CC BY-SA 3.0
Не связан с Stack Overflow