当前位置:网站首页>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
}
边栏推荐
- File system - basic knowledge of disk and detailed introduction to FAT32 file system
- Exploring the mystery of C language program -- C language program compilation and preprocessing
- 算力服务网络:一场多元融合的系统革命
- PE文件基础结构梳理
- 【STL源码剖析】STL六大组件功能与运用(目录)
- 调用系统函数安全方案
- 高速缓存Cache详解(西电考研向)
- 测试/开发程序员,30而立,你是否觉得迷茫?又当何去何从......
- Talking about the advantages of flying book in development work | community essay solicitation
- centos7.3修改mysql默认密码_详解Centos7 修改mysql指定用户的密码
猜你喜欢

常用的软件测试工具清单,请查收。

I've been doing software testing for two years. I'd like to give some advice to girls who are still hesitating

Of the seven levels of software testers, it is said that only 1% can achieve level 7

Application of TSDB in civil aircraft industry

What is the reason for the disconnection of video playback due to the EHOME protocol access of easycvr platform?

3 years of testing experience. I don't even understand what I really need on my resume. I need 20K to open my mouth?

内网学习笔记(5)

一线城市软件测试工资——你拖后腿了吗

罗德与施瓦茨与中关村泛联院合作开展6G技术研究与早期验证

【STL源码剖析】STL六大组件功能与运用(目录)
随机推荐
疫情防控,居家办公,网上授课之心得 | 社区征文
Beescms website penetration test and repair comments "suggestions collection"
F - spices (linear basis)
分布式事务解决方案和代码落地
The Oracle 11g RAC cluster database cannot be started due to directory permission errors
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(4)—— 修改 oracle11g rac 集群的 scanIP
元宇宙的生态圈
测试/开发程序员,30而立,你是否觉得迷茫?又当何去何从......
MCN机构遍地开花:博主和作者要谨慎签约、行业水很深
LINQ query (3)
Kaggle 专利匹配比赛金牌方案赛后总结
多模态情感识别_多模态融合的情感识别研究「建议收藏」
psql 列转行
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(1)——迁移数据到节点1
Multimodal emotion recognition_ Research on emotion recognition based on multimodal fusion
EasyCVR平台EHOME协议接入,视频播放出现断流是什么原因?
I've been doing software testing for two years. I'd like to give some advice to girls who are still hesitating
[I.MX6UL] U-Boot移植(六) 网络驱动修改 LAN8720A
MOS tube related knowledge
一线城市软件测试工资——你拖后腿了吗