1Groovy对Json的操作

1.1 Groovy自带工具处理Json

Groovy中自带能将字符串转换为json的工具包groovy.json.JsonSlurper,也带有将对象转换为json字符串的包groovy.json.JsonOutput。我们在下面的例子中编写代码来进行测试:

package com.dream21th.json

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.json.StringEscapeUtils

def person = new Person(name: "张三丰",age:29)
def personString=JsonOutput.toJson(person)
println(personString)//{"age":29,"name":"\u5f20\u4e09\u4e30"}
println(personString.class)//class java.lang.String

//将Unicode转为中文
def str= StringEscapeUtils.unescapeJava(personString)
println(str)//{"age":29,"name":"张三丰"}
//将中文转为Unicode
//StringEscapeUtils.escapeJava(str)


def personList=[
        new Person(name: "张三丰",age:29),
        new Person(name: "里斯",age:19),
        new Person(name: "王明",age:18),
        new Person(name: "无缘",age:29)
]

def personListString=JsonOutput.toJson(personList)
println(personListString)//[{"age":29,"name":"\u5f20\u4e09\u4e30"},{"age":19,"name":"\u91cc\u65af"},{"age":18,"name":"\u738b\u660e"},{"age":29,"name":"\u65e0\u7f18"}]
//将Unicode转为中文
println(StringEscapeUtils.unescapeJava(personListString))//[{"age":29,"name":"张三丰"},{"age":19,"name":"里斯"},{"age":18,"name":"王明"},{"age":29,"name":"无缘"}]


def personStr='{"age":39,"name":"李莉"}'
def js=new JsonSlurper()
def p =(Person) (js.parseText(personStr))
println(p)//name:李莉,age:39
println(p.class)//class com.dream21th.json.Person

def listStr='[{"age":29,"name":"张三丰"},{"age":19,"name":"里斯"},{"age":18,"name":"王明"},{"age":29,"name":"无缘"}]'
def list1=js.parseText(listStr)
println(list1)//[[age:29, name:张三丰], [age:19, name:里斯], [age:18, name:王明], [age:29, name:无缘]]
println(list1.class)//class java.util.ArrayList

​ 通过上面代码的运行,可以知道Groovy中的自带json工具的使用方式,同时要注意的是,Groovy自带工具在将汉字转换的时候会出现Unicode编码,如果需要转换成中文的话还需要使用StringEscapeUtils.escapeJava方法。下图是上述代码运行时控制台的输出内容:

Groovy操作JSON和XML及对文件的处理-LMLPHP

1.2 使用java第三方类库gson处理json

​ 通过上面对Groovy自带json包对json的处理,发现使用起来还是不是特别方便,比较明显的就是中文会出现Unicode编码,将json字符串转成对象的时候要在前面加上强制类型转换。这些问题可以使用第三方的包gson来避免。

gson包的下载地址: https://repo1.maven.org/maven2/com/google/code/gson/gson/2.9.0/

Groovy操作JSON和XML及对文件的处理-LMLPHP

​ 下载完成之后,将包放到项目的libs目录下面,按照下面的操作将包加入到项目中,选中包点击鼠标右键,选中Add as Library

Groovy操作JSON和XML及对文件的处理-LMLPHP

​ 第三方包依赖完成之后,编写下面代码进行测试,从输出结果来看得到同样的输出代码比Groovy自带json包简单:

package com.dream21th.json

import com.google.gson.Gson

def person = new Person(name: "张三丰",age:29)
def gson=new Gson()
def personString = gson.toJson(person)
println(personString)//{"name":"张三丰","age":29}
println(personString.class)//class java.lang.String

def personStr='{"age":39,"name":"李莉"}'
def p =gson.fromJson(personStr,Person.class)
println(p)//name:李莉,age:39
println(p.class)//class com.dream21th.json.Person

def listStr='[{"age":29,"name":"张三丰"},{"age":19,"name":"里斯"},{"age":18,"name":"王明"},{"age":29,"name":"无缘"}]'
def list1=gson.fromJson(listStr,List.class)
println(list1)//[[age:29, name:张三丰], [age:19, name:里斯], [age:18, name:王明], [age:29, name:无缘]]
println(list1.class)//class java.util.ArrayList

2 Groovy对xml的操作

Groovy自带了对xml的处理工具,将对象转换为xml的工具groovy.xml.MarkupBuilder,将xml转换为对象的处理工具groovy.xml.XmlSlurper,下面我们编写一个例子,将对象转换为xml

2.1 对象转换成xml

​ 首先,定义一个Student的类,该类的具体定义信息如下:

package com.dream21th.xml

class Student {

    int id

    String name

    int age

    String sex

    String phone

    String address

    //方便打印输出
    @Override
    String toString() {
        return "name:"+this.name+",age:"+this.age
    }
}

​ 将对象转换成xml的代码如下:

package com.dream21th.xml

import groovy.xml.MarkupBuilder

def sw=new StringWriter()
def mb=new MarkupBuilder(sw)

def list=[
        new Student(id: 1,name: "张三",age: 18,phone: "13971117777",sex: "男",address: "上海时浦东新区"),
        new Student(id: 2,name: "里斯",age: 19,phone: "13971117777",sex: "男",address: "上海时黄埔"),
        new Student(id: 3,name: "王五",age: 17,phone: "13971117777",sex: "男",address: "上海时嘉定"),
        new Student(id: 4,name: "张敏",age: 18,phone: "13971117777",sex: "女",address: "上海时普陀"),
        new Student(id: 5,name: "丽丽",age: 18,phone: "13971117777",sex: "男",address: "上海时杨浦"),
        new Student(id: 6,name: "王浩",age: 18,phone: "13971117777",sex: "男",address: "上海时浦东新区")
]

def stuStr="students"
mb."${stuStr}"(){
    for (stu in list){
        student(id: stu.id){//student节点标签里面会有一个id,如<student id='1'>
            name(desc:"姓名",stu.name)//name节点标签里面会有一个desc,还有一个值 <name desc='姓名'>张三</name>
            age(value:stu.age)//age节点标签里面有一个value
            phone(stu.phone)
            sex(stu.sex)
            address(stu.address)
        }
    }
}

println(sw) //输出转换成xml后的

​ 将对象转换成xml,在节点中可以定义属性(Student节点中的id),也可以只定义值(phone(stu.phone)),也可以两者都定义name(desc:"姓名",stu.name),上述代码的输出结果信息如下:

<students>
  <student id='1'>
    <name desc='姓名'>张三</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时浦东新区</address>
  </student>
  <student id='2'>
    <name desc='姓名'>里斯</name>
    <age value='19' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时黄埔</address>
  </student>
  <student id='3'>
    <name desc='姓名'>王五</name>
    <age value='17' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时嘉定</address>
  </student>
  <student id='4'>
    <name desc='姓名'>张敏</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时普陀</address>
  </student>
  <student id='5'>
    <name desc='姓名'>丽丽</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时杨浦</address>
  </student>
  <student id='6'>
    <name desc='姓名'>王浩</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex></sex>
    <address>上海时浦东新区</address>
  </student>
</students>
2.2 xml转换成对象

​ 接下来,我们将上面转换的xml解析出来,编写下面代码:

package com.dream21th.xml

import groovy.xml.XmlSlurper

def xml='''
<students>
  <student id='1'>
    <name desc='姓名'>张三</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex>男</sex>
    <address>上海时浦东新区</address>
  </student>
  <student id='2'>
    <name desc='姓名'>里斯</name>
    <age value='19' />
    <phone>13971117777</phone>
    <sex>男</sex>
    <address>上海时黄埔</address>
  </student>
  <student id='3'>
    <name desc='姓名'>王五</name>
    <age value='17' />
    <phone>13971117777</phone>
    <sex>男</sex>
    <address>上海时嘉定</address>
  </student>
  <student id='4'>
    <name desc='姓名'>张敏</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex>女</sex>
    <address>上海时普陀</address>
  </student>
  <student id='5'>
    <name desc='姓名'>丽丽</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex>男</sex>
    <address>上海时杨浦</address>
  </student>
  <student id='6'>
    <name desc='姓名'>王浩</name>
    <age value='18' />
    <phone>13971117777</phone>
    <sex>男</sex>
    <address>上海时浦东新区</address>
  </student>
</students>
'''

def xs = new XmlSlurper()
def students=xs.parseText(xml)
//获取第一个student节点的name的值
println(students.student[0].name.text())//张三

//获取第二个student节点的age节点的value属性值
println(students.student[1].age.@value)//19


students.student.each{
    stu -> printf("student@id:%s name:%s name@desc:%s age@value:%s phone:%s sex:%s address:%s\n",stu.@id,stu.name.text(),stu.name.@desc,stu.age.@value,stu.phone.text(),stu.sex.text(),stu.address.text())
}

​ 代码运行后的输出结果:

student@id:1 name:张三 name@desc:姓名 age@value:18 phone:13971117777 sex:男 address:上海时浦东新区
student@id:2 name:里斯 name@desc:姓名 age@value:19 phone:13971117777 sex:男 address:上海时黄埔
student@id:3 name:王五 name@desc:姓名 age@value:17 phone:13971117777 sex:男 address:上海时嘉定
student@id:4 name:张敏 name@desc:姓名 age@value:18 phone:13971117777 sex:女 address:上海时普陀
student@id:5 name:丽丽 name@desc:姓名 age@value:18 phone:13971117777 sex:男 address:上海时杨浦
student@id:6 name:王浩 name@desc:姓名 age@value:18 phone:13971117777 sex:男 address:上海时浦东新区

​ 通过上面例子,可以发现在解析属性的时候有@+属性值,解析值的时候用值的text方法即可。

3 Groovy操作文件

3.1 文本文件操作

​ 可以在Groovy中对文件进行操作,一次读取文件的所有内容,每次读取一行内容,读取指定字符长度的数据,复制文件的操作,具体代码实现如下:

package com.dream21th.file

def file=new File("./20240103.xml")
file.eachLine {it-> println(it)} //打印文件中的每行内容

def strAll=file.getText() //获取文件中的所有内容
println(strAll)
println(strAll.class)

def list = file.readLines() //将文件中的内容按照行全部读出来放到列表里面

for(line in list){
    println(line)
}

//读取200个字符
def bufenStr=file.withReader {
    def buffer = new char[200]
    it.read(buffer)
    return buffer
}
println(bufenStr)

//复制文件
def copy(String sourcePath,String destPath){
    def destFile=new File(destPath)
    if(!destFile.exists()){
        //如果文件不存在就创建一个文件
        destFile.createNewFile()
    }

    new File(sourcePath).withReader {
        def lines=it.readLines()
        destFile.withWriter {
            lines.each {line->
                it.append(line+"\r\n")
            }
        }
    }
    return true
}

copy("./20240103.xml","./20240103001.xml")
3.2 对象写入文件和从文件中读出

​ 有时候,我们可能需要将对象存到文件里面后面在取出来使用,那么就可以采用本部分的内容,需要存储的对象的类需要序列化也就是要实现Serializable接口。本次代码展示的类信息如下:

package com.dream21th.file

class Student implements Serializable {

    int id

    String name

    int age

    String sex

    String phone

    String address

    //方便打印输出
    @Override
    String toString() {
        return "name:"+this.name+",age:"+this.age
    }
}

​ 下面操作时将对象存到文件:

def saveObject(Object object,String path){
    def destFile=new File(path)
    if(!destFile.exists()){
        //如果文件不存在就创建一个文件
        destFile.createNewFile()
    }

    destFile.withObjectOutputStream {
        it.writeObject(object)
    }
}


def  student = new Student(id: 1,name: "张三",age: 18,phone: "13971117777",sex: "男",address: "上海时浦东新区")
saveObject(student,"./20240103002.txt")

​ 下面代码是从文件中读取上面存的对象:

def readObject(String path){
    def object =null
    def file=new File(path)
    if(file==null || !file.exists()){
        return null
    }
    file.withObjectInputStream {
        object=it.readObject()
    }
    return object
}

def s2=(Student)readObject("./20240103002.txt")
println(s2)
01-04 12:25