美文网首页
5、xml解析、json解析、文件读写

5、xml解析、json解析、文件读写

作者: 最美下雨天 | 来源:发表于2019-03-11 15:51 被阅读0次
    image.png

    首先需要说明,java中对json的操作,像什么fastjson、gson在groovy中都是可以实现的,但是在groovy中提供了更简便的方式

    import groovy.json.JsonSlurper
    def reponse ='''
    {
      "data" : {
        "curPage" : 1,
        "offset" : 0,
        "over" : false,
        "pageCount" : 20,
        "size" : 15,
        "total" : 296
      },
      "errorCode" : 0,
      "errorMsg" : ""
    }
    '''
    def jsonSluper=new JsonSlurper()
    def text=jsonSluper.parseText(reponse)
    println text.data.total //输出296
    
    
    

    xml

    import groovy.xml.MarkupBuilder
    
    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 result=xmlSluper.parseText(xml)
    println result.value.books[0].book[0].title.text()  //输出:疯狂Android讲义
    println result.value.books[0].book[0].author.text()  //输出:李刚
    println result.value.books[0].book[0].@available  //输出:20
    println result.value.books[0].book[0].author.@id  //输出:1
    
    //找到所有作者是李刚的书籍的名字
    def results=[]  //java.util.ArrayList
    result.value.books.each{
        bs->
            bs.book.each{
                b->
                    if(b.author.text().equals('李刚'))
                    {
                        results.add(b.title)
                    }
            }
    }
    
    println results.class
    println results.toListString() //输出:[疯狂Android讲义, Vue从入门到精通]
    
    //深度遍历
    def deps=result.depthFirst().findAll {
        book->
            book.author.text()=='李刚' ? true:false
    }
    println deps.toListString() //输出:[疯狂Android讲义李刚, Vue从入门到精通李刚]
    
    
    //广度遍历
    //查找id为2的book节点
    def book=result.value.books.children().findAll{
        node->
            node.name()=='book'&& node.@id=='2'
    }
    
    println book.title.text()   //[第一行代码]
    
    
    
    
    //生成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)//核心类
    /*xmlBuilder.langs(type:'current',count:'3',mainstream:'true')
            {
                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数据
    class language
    {
        String flavor
        String version
        String value
    }
    
    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.6.0',value:'Groovy'),
                new language(flavor:'dynamic',version:'1.9',value:'JavaScript')
        ]
    }
    
    def ls=new langs()
    xmlBuilder.langs(type:ls.type,count:ls.count,mainstream: ls.mainstream)
            {
                ls.languages.each {
                    l->
                        language(flavor:  l.flavor,version:  l.version,value:  l.value)
                }
            }
    
    println sw
    
    

    文件

    def file=new File('../groovyfirst.iml')
    file.eachLine {
        println it  //可以获取每一行
    }
    
    println file.text //获取整个文档内容
    
    //读取文件部分内容
    def reader=file.withReader {
        it->
            char[] buffer=new char[100]
            it.read(buffer)
            return buffer
    }
    
    println reader
    
    
    
    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
    }
    
    
    
    def person = new Person(name: 'Qndroid', 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
    }
    
    image.png image.png

    相关文章

      网友评论

          本文标题:5、xml解析、json解析、文件读写

          本文链接:https://www.haomeiwen.com/subject/unvrpqtx.html