json操作
class Person implements Serializable {
String name
Integer age
def increaseAge(Integer years) {
this.age += years
}
/**
* 一个方法找不到时,调用它代替
*/
def invokeMethod(String name, Object args) {
return "the method is ${name}, the params is ${args}"
}
def methodMissing(String name, Object args) {
return "the method ${name} is missing"
}
}
def list = [
new Person(name:'john',age: 25),
new Person(name:'major',age: 26)
]
println JsonOutput.toJson(list)
[{“age”:25,“name”:“john”},{“age”:26,“name”:“major”}]
换种方式输出:
def list = [
new Person(name:'john',age: 25),
new Person(name:'major',age: 26)
]
def json = JsonOutput.toJson(list)
println JsonOutput.prettyPrint(json)
[
{
"age": 25,
"name": "john"
},
{
"age": 26,
"name": "major"
}
]
String转Json对象
def list = [
new Person(name:'john',age: 25),
new Person(name:'major',age: 26)
]
def json = JsonOutput.toJson(list)
//将json转化为实体对象
def jsonSluper = new JsonSlurper()
println jsonSluper.parseText(json)
[[age:25, name:john], [age:26, name:major]]
使用Gson
新建libs目录将gson的jar包添加进去,并右键-“add library”
Gson gson = new Gson()
println gson.toJson(obj)
解析网络请求返回的数据
def getNetworkData(String url) {
//发送http请求
def connection = new URL(url).openConnection()
connection.setRequestMethod('GET')
connection.connect()
def response = connection.content.text
//将json转化为实体对象
def jsonSluper = new JsonSlurper()
return jsonSluper.parseText(response)
}
def reponse =
getNetworkData(
'https://suggest.taobao.com/sug?code=utf-8&q=卫衣')
println reponse.result
println reponse.result[0]
[[卫衣男, 687138.4639665817], [卫衣女, 1110721.0577841266], [卫衣女宽松韩版, 875439.7113084032], [卫衣男秋冬款, 47417.59851305052], [卫衣加厚加绒女, 502985.8417910735], [卫衣女潮ins, 193586.07302913623], [卫衣男连帽, 379002.6325483171], [卫衣女秋冬, 991265.3859512259], [卫衣男潮, 736003.5654852428], [卫衣女2019新款潮, 800607.7791193472]]
[卫衣男, 687138.4639665817]
xml文件操作
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[0].book[0].@available
20
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.toListString()
[疯狂Android讲义, Vue从入门到精通]
//深度遍历xml数据
def titles = response.depthFirst().findAll { book ->
return book.author.text() == '李刚' ? true : false
}
println titles.toListString()
[疯狂Android讲义李刚, Vue从入门到精通李刚]
//广度遍历xml数据
def name = response.value.books.children().findAll { node ->
node.name() == 'book' && node.@id == '2'
}.collect { node ->
return node.title.text()
}
println name
[第一行代码]
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') {
age('16')
}
language(flavor: 'dynamic', version: '1.6') {
age('10')
}
language(flavor: 'dynamic', version: '1.9', 'JavaScript')
}
println sw
打印结果:
<langs type='current' count='3' mainstream='true'>
<language flavor='static' version='1.5'>
<age>16</age>
</language>
<language flavor='dynamic' version='1.6'>
<age>10</age>
</language>
<language flavor='dynamic' version='1.9'>JavaScript</language>
</langs>
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
}
<langs type='current' count='3' mainstream='true'>
<language flavor='static' version='1.5'>Java</language>
<language flavor='dynamic' version='1.3'>Groovy</language>
<language flavor='dynamic' version='1.6'>JavaScript</language>
</langs>
json与xml互相转化
文件处理
所有java对文件的处理类,groovy都可以使用
def file = new File('../../groovy.iml')
file.eachLine { line ->
println line
}
打印:
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="groovy-2.5.8 (2)" level="application" />
<orderEntry type="library" name="gson-2.8.2" level="project" />
</component>
</module>
也可以使用getText方法获取文件内容
def text = file.getText()
println text
//读取文件部分内容
def reader = file.withReader { reader ->
char[] buffer = new char[100]
reader.read(buffer)
return buffer
}
println reader
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="Ne
文件拷贝
def result = copy('../../groovy.iml'
, '../../groovy2.iml')
println result
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
}
true
对象的保存和文件读取
def person = new Person(name: 'hongxue', age: 26)
saveObject(person, '../../person.bin')
def result = (Person) readObject('../../person.bin')
println "the name is ${result.name} and the age is ${result.age}"
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
}
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
}
the name is hongxue and the age is 26