一、json操作详解
def list = [new Person(name: "John", age: 22),
new Person(name: 'Major', age: 33)]
def json = JsonOutput.toJson(list)
println json
println JsonOutput.prettyPrint(json)
def response = getNetworkData('https://restapi.amap.com/v3/weather/weatherInfo?city=%E9%95%BF%E6%B2%99&' +
'key=13cb58f5884f9749287abbead9c658f2')
def json2 = JsonOutput.toJson(response)
println json2
println JsonOutput.prettyPrint(json2)
println response
println response.lives
def getNetworkData(String url) {
//发送http请求
def connection = new URL(url).openConnection()
connection.setRequestMethod('GET')
connection.connect()
def response = connection.content.text
//将json转化为实体对象
def jsonSlurper = new JsonSlurper()
return jsonSlurper.parseText(response)
}
二、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 xmlSlurper = new XmlSlurper()
def response = xmlSlurper.parseText(xml)
println response
println response.value.books[0].book[0].title.text()
println response.value.books[1].book[0].@available
//查询作者为李刚的书名
def list = []
response.value.books.each { books ->
//对书名进行遍历
books.book.each { book ->
def author = book.author.text()
if (author.equals('李刚')) {
list.add(book.title.text())
}
}
}
println list
//深度遍历xml数据 depthFirst()等同于 '**'
def titles = response.depthFirst().findAll {
book -> return book.author.text() == '李刚'
}
println titles
//广度遍历xml数据 children()等同于 '*'
def names = response.value.books.children().findAll { node ->
node.name() == 'book' && node.@id == '1'
}.collect {node ->
return node.title.text()
}
println names
三、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')
language(flavor: 'static', version: '1.5') {
age('16')
}
}
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: 'static', version: '1.6.0', value: 'Groovy'),
new Language(flavor: 'static', version: '1.9', value: 'JavaScript')]
}
//对应xml中的language节点
class Language {
String flavor
String version
String value
}
def sw2 = new StringWriter()
def xmlBuilder2 = new MarkupBuilder(sw2)
def langs = new Langs()
xmlBuilder2.langs(type: langs.type, count: langs.count,
mainstream: langs.mainstream) {
//遍历所有的子结点
langs.languages.each { lang ->
language(flavor: lang.flavor,
version: lang.version, lang.value)
}
}
println sw2
四、groovy文件处理详解
def file = new File('D:\\idea_ws\\test\\GroovyTest\\GroovyTest1\\GroovyTest1.iml')
file.eachLine { line ->
// println line
}
//读取文件内容 String
def text = file.getText()
//println text
//读取文件内容 返回List<String>
def res = file.readLines()
//读取文件部分内容
def reader = file.withReader { reader ->
char[] buffer = new char[100]
reader.read(buffer)
return buffer
}
//println reader
//拷贝文件
def copy(String sourcePath, String targetPath) {
try {
//首先创建目标文件
def tarFile = new File(targetPath)
if (!tarFile.exists()) {
tarFile.createNewFile()
}
//开始copy
def sourFile = new File(sourcePath)
if (sourFile.exists()) {
sourFile.withReader { reader ->
def lines = reader.readLines()
tarFile.withWriter { writer ->
lines.each { line ->
writer.append(line + "\r\n")
}
}
}
}
return true
} catch (Exception e) {
e.printStackTrace()
}
return false
}
def res2 = copy('D:\\idea_ws\\test\\GroovyTest\\GroovyTest1\\GroovyTest1.iml',
'../../../GroovyTest2.iml')
//println res2
def saveObject(Object object, String targetPath) {
try {
//首先创建目标文件
def tarFile = new File(targetPath)
if (!tarFile.exists()) {
tarFile.createNewFile()
}
tarFile.withObjectOutputStream { out ->
out.writeObject(object)
}
return true
} catch (Exception e) {
e.printStackTrace()
}
return false
}
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) {
e.printStackTrace()
}
return obj
}
def person = new Person(name: 'song', age: 27)
//saveObject(person, '../../../Person.bin')
def res3 = (Person) readObject('../../../Person.bin')
println res3.name + ',' + res3.age