Suche…
Parse einen Json-String
import groovy.json.JsonSlurper;
def jsonSlurper = new JsonSlurper()
def obj = jsonSlurper.parseText('{ "foo": "bar", "baz": [1] }')
assert obj.foo == 'bar'
assert obj.baz == [1]
Parsen Sie eine Json-Datei
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)
Schreibe einen Json in einen String
import groovy.json.JsonOutput;
def json = JsonOutput.toJson([foo: 'bar', baz: [1]])
assert json == '{"foo":"bar","baz":[1]}'
Zusätzlich zu den Karten, Listen und Primitiven groovy.json.JsonOutput
auch eine POJOs serialitzation unterstützt:
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"}]'
Drucke einen Json String
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
]
}'''
Schreiben Sie einen Json in eine Datei
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
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow