groovy高级语法

news/2024/5/20 5:08:10 标签: android, groovy, gradle

文章目录

  • json操作
  • xml文件操作
    • xml解析
    • xml文件生成
  • 文件处理

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


http://www.niftyadmin.cn/n/1838341.html

相关文章

计算机视觉行业博客和代码汇总

每个做过或者正在做研究工作的人都会关注一些自己认为有价值的、活跃的研究组和个人的主页&#xff0c;关注他们的主页有时候比盲目的去搜索一些论文有用多了&#xff0c;大牛的或者活跃的研究者主页往往提供了他们的最新研究线索&#xff0c;顺便还可八一下各位大牛的经历&…

php中策略模式中浏览器判定

<?phpabstract class baseAgent{abstract function PrintPage();}class ieAgent extends baseAgent{function PrintPage(){return "当前浏览器是IE!";}}class otherAgent extends baseAgent{function PrintPage(){return "当前浏览器不是IE!";}}if(str…

groovy简介和环境搭建

文章目录1 groovy简介2 groovy环境搭建来自慕课课程的笔记&#xff1a;https://coding.imooc.com/learn/list/206.html1 groovy简介 领域特定语言DSL DSL&#xff1a;domain specific language 与通用语言的区别:核心思想&#xff1a;求专不求全&#xff0c;解决特定问题 gr…

腾讯如何用Elasticsearch挖掘万亿数据价值?

Elasticsearch&#xff08;ES&#xff09;作为开源首选的分布式搜索分析引擎&#xff0c;通过一套系统轻松满足用户的日志实时分析、全文检索、结构化数据分析等多种需求&#xff0c;大幅降低大数据时代挖掘数据价值的成本。腾讯在公司内部丰富的场景中大规模使用ES&#xff0c…

QQ全量上云的技术解析

腾讯的业务体量非常庞大&#xff0c;在2019年&#xff0c;腾讯已拥有超过了100万台服务器&#xff0c;其中&#xff0c;社交业务包括QQ和空间的体量有近20万台服务器&#xff0c;且分布在全国三地。 把QQ这头大象搬到云上并非易事。作为腾讯最庞大、最悠久、最复杂的业务之一&…

Oracle RAC ASM 实例 从10.2.0.1 升级到 10.2.0.4 说明

一. 说明 在官网看到一篇ASM 升级的文档&#xff0c;如下&#xff1a; How To Upgrade ASM from 10.2 to 11.1 (RAC) http://blog.csdn.net/tianlesoftware/archive/2011/04/25/6362083.aspx Unable To Open Database After ASM Upgrade From Release 11.1 To Release 11.2 htt…

Gradle核心之Project详解

文章目录project相关apigetAllprojectsgetSubprojectsgetParentprojectallprojectssubprojects属性相关api定义扩展属性定义扩展属性2文件属性路径获取相关api文件操作相关api文件定位文件拷贝文件树遍历其他api依赖相关apibuildscript执行外部命令新建项目&#xff0c;添加lib…

企业数据安全如何做,专家给你5条建议

引言&#xff1a;数据安全对企业生存发展有着举足轻重的影响&#xff0c;数据资产的外泄、破坏都会导致企业无可挽回的经济损失和核心竞争力缺失&#xff0c;而往往绝大多数中小企业侧重的是业务的快速发展&#xff0c;忽略了数据安全重要性。近年来&#xff0c;企业由于自身的…