创建Json
直接使用”“”{“name”:”testUser”}”“”,这个比较简单
def tasks = [1, 2, 3] def data = [ success: true, count : tasks.size(), data : tasks.collect { [id: it] } ] def builder = new JsonBuilder(data) println builder
def builder = new JsonBuilder(data) builder { first 'zhaopf' last 'haha' //传入map test( a: 'a', b: 'b' ) married true //传入list conferences({ a 'a' b 'b' }, { a 'a' b 'b' }) } println builder println JsonOutput.prettyPrint(builder.toString())
解析Json
class Person {
def first
def last
}
def p = new Person(first: 'testUser', last: 'haha')
def b = new JsonBuilder(p) println b.toString()
println JsonOutput.toJson(p) //格式化json数据 println JsonOutput.prettyPrint(JsonOutput.toJson(p))
def slurper = new JsonSlurper() Person person = slurper.parseText(JsonOutput.toJson(p)) println person println person.first println person.last
创建XML
“”“<html><⁄html>”“”
直接把线程的xml写入
new File(“baidu.html”).write(“https://www.baidu.com/“.toURL().text)//将xml写入到当前路径下的normal.html中 def fw = new FileWriter(new File("normal.html")) def builder = new MarkupBuilder(fw) builder.html { br{} //写入注释 mkp.comment("测试") head("hello", m: 'a') { title("testTitle", m: 'a') } body("hello", m: 'a') { title("testTitle2", m: 'a') } }
def sb = new StreamingMarkupBuilder() sb.encoding = 'UTF-8' def closure = { mkp.xmlDeclaration() html { head(id: 1) { } } } def sw = sb.bind(closure) println sw.toString()
解析XML
def parser = new XmlParser().parse("AndroidManifest.xml")
//命名空间:xmlns:android="http://schemas.android.com/apk/res/android"
def ns = new Namespace('http://schemas.android.com/apk/res/android', 'android')
//Node node1 = parser.application[0].activity[0]
//println node1.attributes()[ns.name]
//Node node2 = parser.application[0].activity[1]
//println node2.attributes()[ns.name]
//获得application节点
Node node = parser.application[0]
//NodeList
Node meta = node.'meta-data'[0]
//删除一个节点
node.remove(meta)
//添加一个节点
node.appendNode('meta-data', [(ns.name): 'a', (ns.value): 'b', (ns.hh): 'hh'])
//将xml写入到当前路径下的replace.xml中
new XmlNodePrinter(new PrintWriter(new File("replace.xml"))).print(parser)
Swing
groovy中我们是这样写的
def builder = new SwingBuilder()
def swing = builder.frame(
title: '测试',
size: [100, 100],
layout: new FlowLayout(),
defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE) {
label(text: '文本')
button(text: '按钮', actionPerformed: {
println "点击"
})
}
swing.setVisible(true)
而在java中
def frame = new Frame()
frame.setTitle('测试')
frame.setSize(100, 100)
frame.setLayout(new FlowLayout())
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
new Label()
new JButton().addActionListener {
};