Android Gradle learning series (4) -Gradle advanced usage combat

Foreword

GroovyThe basic grammar we mainly explained Groovyin the last few articles , this article is the advanced grammar we mainly explained

json operation, xml operation, file operation

1. Detailed explanation of Json operation

JsonThere are basically two related operations, one is to Jsonconvert a string into an entity object. One is to convert our entity object into a corresponding Jsonstring. Then we Groovyhave corresponding classes and methods to help us

groovy.json.JsonSlurper: convert jsondata to entity objects groovy.json.JsonOutput: convert entity objects to jsondata

1.1 Use the own method

Let's write an example to see the effect

The first: the physical object is converted to Json
Insert picture description here
the same time Groovyalso comes with a direct way to help me format
Insert picture description here
second: json will turn into a solid object
Insert picture description here
that parseTextthe parameter is String, we generally use the word can be used directly parse, the parameters of this method is basically Support any type, not justString
Insert picture description here

1.2 Using third-party libraries

We know that it Groovyis fully compatible Java, so Javathe third-party jsonlibraries that can be used (such as:, gsonor fastjsonwhatever Groovycan also be imported and used in China, but the one Groovythat comes with it is actually enough for us

Let's talk about how to import the jar package gson
downloaded first gson, put it in our libs directory ( download address ),
Insert picture description here
and then directly import the corresponding class in the script file and use the corresponding method.
Insert picture description here

1.3 Analysis of simulated network requests

We actually basically request data from the server, the client converts it into our entity object, and then displays our entity object on our UI or storage local.This
Insert picture description here
is a Javalittle different from ours , Javain which you need to define a specific Entity class to parse, get the corresponding data after parsing, but Groovythere is no need to define a specific entity class, we can directly get the data we want

2.xml detailed operation

Insert picture description here
The above mind map is Javatwo ways to process data in xml format, and we Groovyprovide the corresponding xml processing tool directly

groovy.xml.XmlSlurper: convert xml raw data into entity objects groovy.xml.MarkupBuilder: convert entity objects into xml data

Below we will use

2.1 Groovy parsing xml

We first define an 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>
'''

JsonThere was one in the operation before JsonSlurper, then the corresponding one xmlwill meet by chance.It XmlSlurperalso has a parsemethod, which is basically the JsonSlurpersame as yours above .

For example, we want to output the name of the first book: Crazy Android Lectures, what should we do?
Insert picture description here
We found it is very simple and much more Javaconvenient than ours , then what if we want to output the label attribute? For example, to obtain the available attribute of a book
Insert picture description here

2.2 Traverse XML

What should we do if we want to obtain xmla collection of all the books whose author is Li Gang?
Here our logic should be to find the layers one by one, find booksthe collection at the first layer response.value.books, then traverse this books, find each one book, and take it the authorlook is not called Gang
Insert picture description here
we see the results of our output is the correct result, but Groovyin fact, provide a more simple method of traversing
deep traversal depthFirst, we have achieved in this way under the effect of the above
Insert picture description here
result is the same, but below this This method is easier to use

Deep traversal naturally has breadth traversal children(), for example, we want to get the name of the book whose tag attribute id is 2.
Insert picture description here

2.3 Generate XML

GroovyYou can also generate what you want xml, for example, if we think about generating the following one, what xmlshould we do?

/**
 * 生成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>
 */

First of all, let's analyze the one we want to generate.It xmlhas two nodes, one is langs, the attributes are : type,count.mainstream, langsthere is another node under the node language, the attribute is : flavor,version, and then value
after the corresponding analysis is cleared, we start to write MarkupBuilderYes, a class will be used here . This class is xmlthe core class for generating data.
Insert picture description here
If languagethere is a node below, how to get it? languageSame as the node we specified
Insert picture description here

But in general, in actual development, we often convert entity objects into the xmlsame way as above.
We first build a Languageclass

//对应xml中的language节点
class Language {
    String flavor
    String version
    String value
}

Then build a Langsclass

//对应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.6.0', value: 'Groovy'),
            new Language(flavor: 'dynamic', version: '1.9', value: 'JavaScript')
    ]

}

Then we generate one according to our writing above xml,
Insert picture description here
we can also Jsoncombine it with us , the Jsonstring JsonSlurpergenerates the entity class, and then MarkupBuildergenerates the correspondingxml

3. Detailed file operations

Insert picture description here
Import thinking above us Javain the handling of files in Groovyyou can use these methods, but Groovyalso extends a number of more efficient and powerful methods (ResourceGroovyMethods)
then we have a few examples to the specific practices
Insert picture description here
we take on The examples here take this file as an example, it is automatically generated when the project is created, and the
creation Fileobject is Javaexactly the same as ours.
Insert picture description here

3.1 traverse the file

We first output the contents of this file, here we need to use eachLinethis method
Insert picture description here

3.2 Get all the contents of the file

This is the same as our output above
Insert picture description here

3.3 Get a list of each line of text

Get each line of text list
This method returns a list of each line in our file as an element

3.4 Reading a part of a file

We get the first 100 characters of the file
Insert picture description here

3.5 Copy files

Insert picture description here
We copied it line by line here, and we can also copy it all at once, we call this method
Insert picture description here

We see a file copied successfully, we open this file
Insert picture description here

It is exactly the same as the content of the source file.There
is also a place to note Javahere.We need to manually close the stream when reading and writing files in, but Groovywe can omit this step in because we have done it for
us internally.Let's take a look at the withWritermethod first
Insert picture description here

Continue to go down,
Insert picture description here
let's look at finallythe method inside
Insert picture description here

3.6 Save the object to a file

A new method is used here withObjectOutputStream, we use text reader和writer, we use objectsstream
Insert picture description here

Let's write an example to verify that
Insert picture description here
we should pay attention here: this object must implement the serialization interface, otherwise it will report an error

Insert picture description here

3.7 Remove the object from the file

Insert picture description here

We take the one we just saved person
Insert picture description here
and we can see that it is the same as what we saved

OK, here we are finished like this, we will start learning Gradlefrom the next article, see you in the next article

Published 87 original articles · Like 319 · Visit 1.49 million +

Guess you like

Origin blog.csdn.net/Greathfs/article/details/102809322