当前位置:网站首页>Groovy之高级用法
Groovy之高级用法
2022-06-24 23:01:00 【悠然予夏】
1、JSON的序列化与反序列化
1.1、将数据转为JSON
Groovy中提供了JsonOutput这个类,调用里面的方法,可以帮我们将数据转为JSON
def list = [new Person(name: 'John', age: 25),
new Person(name: 'Jack', age: 18)]
// println JsonOutput.toJson(list) // 将列表转为json
def json = JsonOutput.toJson(list)
println JsonOutput.prettyPrint(json) // 带格式的JSON输出方式1.2、将JSON转为原始数据
Groovy中提供了JsonSlurper,调用里面的方法可以进行JSON的反序列化
def jsonSlurper = new JsonSlurper()
println jsonSlurper.parseText(json)注意:如果我们不想使用Groovy中自带的JSON转换工具,也可以通过导入jar包方式,使用其他的JSON转换工具,Groovy完全支持Java中的JSON序列化工具。
2、xml文件的解析和创建
2.1、 解析xml
解析xml文件需要使用Groovy中的XmlSlurper工具类,它极大地简化了Java中xml读取方法。
final String xml = '''
<response version-api="2.0">
<value>
<books id="1" classification="android">
<book available="20" id="1">
<title>疯狂Android讲义</title>
<author id="1">李刚</author>
</book>
<book available="14" id="2">
<title>第一行代码</title>
<author id="2">郭林</author>
</book>
<book available="13" id="3">
<title>Android开发艺术探索</title>
<author id="3">任玉刚</author>
</book>
<book available="5" id="4">
<title>Android源码设计模式</title>
<author id="4">何红辉</author>
</book>
</books>
<books id="2" classification="web">
<book available="10" id="1">
<title>Vue从入门到精通</title>
<author id="4">李刚</author>
</book>
</books>
</value>
</response>
'''
// 解析xml
def xmlSluper = new XmlSlurper()
def response = xmlSluper.parseText(xml)
println response.value.books[0].book[0].title.text() // 疯狂Android讲义
println response.value.books[1].book[0][email protected] // 102.2、xml文件的遍历
案例:查找所有书籍作者为李刚的书
普通方式
def list = []
response.value.books.each { books ->
// 下面对书节点进行遍历
books.book.each { book ->
def author = book.author.text()
if (author.equals("李刚")) {
list.add(book.title.text())
}
}
}Groovy中的深度递归遍历方式
// groovy中为我们提供了递归深度遍历方法,极大地简化了代码
def titles = response.depthFirst().findAll { book -> // depthFirst()还可以使用"**"代替
return book.author.text() == '李刚' ? true : false
}Groovy中的广度递归遍历方式
// 广度遍历xml
def name = response.value.books.children().findAll { node -> // children方法可以用操作符'*'代替, def name = response.value.books.'*'.findAll
node.name() == 'book' && [email protected] == '2' // 查找节点名称为book且id=2的书籍
}.collect { node ->
return node.title.text()
}2.3、xml文件的创建
借助于Groovy中的MarkupBuilder核心类,调用里面的方法,进行xml格式数据的生成
/**
* 生成xml格式数据
* <langs type='current' count='3' mainstream='true'>
<language flavor='static' version='1.5'>Java</language>
<language flavor='dynamic' version='1.6.0'>Groovy</language>
<language flavor='dynamic' version='1.9'>JavaScript</language>
</langs>
*/
def sw = new StringWriter();
def xmlBuilder = new MarkupBuilder(sw) // 用来生成xml数据的核心类
// 创建根节点langs
xmlBuilder.langs(type: 'current', count: '3', mainstream: 'true') {
// 创建子节点language
language(flavor: 'static',version:'1.5','Java') // 不指定属性名,就代表节点的值
language(flavor: 'dynamic',version:'1.6.0','Groovy')
language(flavor: 'dynamic',version:'1.9','JavaScript')
}
println sw动态生成xml数据
def sw = new StringWriter();
def xmlBuilder = new MarkupBuilder(sw) // 用来生成xml数据的核心类
def langs = new Langs()
xmlBuilder.langs(type: langs.type, count: langs.count,
mainstream: langs.mainstream) {
//遍历所有的子结点
langs.languages.each { lang ->
language(flavor: lang.flavor,
version: lang.version, lang.value)
}
}
println sw
//对应xml中的langs结点
class Langs {
String type = 'current'
int count = 3
boolean mainstream = true
def languages = [
new Language(flavor: 'static',
version: '1.5', value: 'Java'),
new Language(flavor: 'dynamic',
version: '1.3', value: 'Groovy'),
new Language(flavor: 'dynamic',
version: '1.6', value: 'JavaScript')
]
}
//对应xml中的languang结点
class Language {
String flavor
String version
String value
}3、文件操作
3.1、读取文件
方法一:使用eachLine方法遍历读取文件
def file = new File('xmlStudy.groovy')
file.eachLine {line ->
println line
}方式二:使用getText方法获取文件全部内容
def text = file.getText() // 获取文件内容
println text方式三:使用readLines方法把读取到的文件放入list列表中
def result = file.readLines() 方式四:借助withReader方法读取文件部分内容
def file = new File('test.txt')
def reader = file.withReader { reader ->
char[] buffer = new char[100]
reader.read(buffer)
return buffer
}3.2、文件的写入
对文件进行写入使用withWriter方法
def file = new File('test.txt')
def writer = file.withWriter { write ->
def Test = "我爱Java"
def buffer = Test.getBytes()
write.write(buffer)
return buffer
}3.3、文件拷贝(读写相结合)
def copy(String sourcePath, String destationPath) {
try {
// 首先创建目标文件
def desFile = new File(destationPath)
if (!desFile.exists()) {
desFile.createNewFile()
}
// 开始copy
new File(sourcePath).withReader { reader ->
def lines = reader.readLines()
desFile.withWriter() { writer ->
lines.each { line ->
writer.append(line + "\r\n")
}
}
}
return true
} catch (Exception e) {
e.printStackTrace()
}
return false
}
// Groovy中调用它的文件操作方法,不需要关闭流,因为它的这个方法中已经设置了流的关闭操作。4、对象的写入与读取、
4.1、将对象写入到文件
借助于withObjectOutputStream方法,我们可以将对象写入到文件中去
def saveObject(Object object, String path) {
try {
// 首先创建目标文件
def desFile = new File(path)
if (!desFile.exists()) {
desFile.createNewFile()
}
desFile.withObjectOutputStream { out ->
out.writeObject(object) // 将对象写入文件
}
return true
} catch (Exception e) {
}
return false
}4.2、从文件中读取对象
借助于withObjectInputStream方法,我们可以将对象从文件中读取出来
def readObject(String path) {
def obj = null
try {
def file = new File(path)
if (file == null || !file.exists()) return null
// 从文件中读取对象
file.withObjectInputStream { input ->
obj = input.readObject()
}
} catch (Exception e) {
}
return obj
}
边栏推荐
- MOS管相关知识
- How to quickly familiarize yourself with the code when you join a new company?
- Lizuofan, co-founder of nonconvex: Taking quantification as his lifelong career
- Exploring the mystery of C language program -- C language program compilation and preprocessing
- Practice and Thinking on process memory
- 探索C语言程序奥秘——C语言程序编译与预处理
- June 24, 2022: golang multiple choice question, what does the following golang code output? A:1; B:3; C:4; D: Compilation failed. package main import ( “f
- Once beego failed to find bee after passing the go get command Exe's pit
- 把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(2)——将数据库转换为集群模式
- [STL source code analysis] configurator (to be supplemented)
猜你喜欢

转行软件测试2年了,给还在犹豫的女生一点建议

背了八股文,六月赢麻了……

如何通过EasyCVR接口监测日志观察平台拉流情况?

做软件安全测试的作用,如何寻找软件安全测试公司出具报告?

都2022年了,你还不了解什么是性能测试?
![Planification du réseau | [quatre couches de réseau] points de connaissance et exemples](/img/c3/d7f382409e99eeee4dcf4f50f1a259.png)
Planification du réseau | [quatre couches de réseau] points de connaissance et exemples

Left hand dreams right hand responsibilities GAC Honda not only pays attention to sales but also children's safety

探索C语言程序奥秘——C语言程序编译与预处理

Experience of epidemic prevention and control, home office and online teaching | community essay solicitation

Intranet learning notes (7)
随机推荐
beescms网站渗透测试和修复意见「建议收藏」
元宇宙的生态圈
Beescms website penetration test and repair comments "suggestions collection"
算力服务网络:一场多元融合的系统革命
Resolution of cross reference in IDA
入坑机器学习:一,绪论
【直播回顾】战码先锋第七期:三方应用开发者如何为开源做贡献
1-6搭建Win7虚拟机环境
Random list random generation of non repeating numbers
Smartctl opens the device and encounters permission denied problem troubleshooting process record
高速缓存Cache详解(西电考研向)
After reciting the eight part essay, I won the hemp in June
js正则匹配数字、大小写字母、下划线、中线和点[通俗易懂]
How do the TMUX color palette work?
qt打包exe文件,解决“无法定位程序输入点_ZdaPvj于动态链接库Qt5Cored.dll”
Is it out of reach to enter Ali as a tester? Here may be the answer you want
内网学习笔记(5)
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(3)—— 把数据库设置为归档模式
华泰证券如何开户能做到万分之一?证券开户安全可靠吗
It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets