当前位置:网站首页>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
}
边栏推荐
- Jetson Nano 从入门到实战(案例:Opencv配置、人脸检测、二维码检测)
- Qt中使用QDomDocument操作XML文件
- Sumati gamefi ecological overview, element design in the magical world
- 元宇宙的生态圈
- After reciting the eight part essay, I won the hemp in June
- DDD concept is complex and difficult to understand. How to design code implementation model in practice?
- Squid 代理服务器之 ACL 访问控制
- [I.MX6UL] U-Boot移植(六) 网络驱动修改 LAN8720A
- Can automate - 10k, can automate - 20K, do you understand automated testing?
- 左手梦想 右手责任 广汽本田不光关注销量 还有儿童安全
猜你喜欢

計網 | 【四 網絡層】知識點及例題

File system - basic knowledge of disk and detailed introduction to FAT32 file system

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

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

会自动化—10K,能做自动化—20K,你搞懂自动化测试没有?

1-6搭建Win7虚拟机环境

进入阿里做测试员遥不可及?这里或许有你想要的答案
![[live review] battle code pioneer phase 7: how third-party application developers contribute to open source](/img/ad/26a302ca724177e37fe123f8b75e4e.png)
[live review] battle code pioneer phase 7: how third-party application developers contribute to open source

After reciting the eight part essay, I won the hemp in June

罗德与施瓦茨与中关村泛联院合作开展6G技术研究与早期验证
随机推荐
|遇到bug怎么分析,专业总结分析来了
random list随机生成不重复数
【移动端】手机界面的设计尺寸
Please run IDA with elevated permissons for local debugging.
产业互联网的概念里有「互联网」字眼,但却是一个和互联网并不关联的存在
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(2)——将数据库转换为集群模式
Random list random generation of non repeating numbers
高速缓存Cache详解(西电考研向)
如何通过EasyCVR接口监测日志观察平台拉流情况?
对进程内存的实践和思考
Intranet learning notes (7)
内网学习笔记(6)
Talking about the advantages of flying book in development work | community essay solicitation
02 common codes for Epicor secondary development
After reciting the eight part essay, I won the hemp in June
Folding screen will become an important weapon for domestic mobile phones to share the apple market
Kaggle 专利匹配比赛金牌方案赛后总结
1-6搭建Win7虚拟机环境
F - Spices(线性基)
[live review] battle code pioneer phase 7: how third-party application developers contribute to open source