Foreword
Groovy
The basic grammar we mainly explained Groovy
in 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
Json
There are basically two related operations, one is to Json
convert a string into an entity object. One is to convert our entity object into a corresponding Json
string. Then we Groovy
have corresponding classes and methods to help us
groovy.json.JsonSlurper: convert
json
data to entity objects groovy.json.JsonOutput: convert entity objects tojson
data
1.1 Use the own method
Let's write an example to see the effect
The first: the physical object is converted to Json
the same time Groovy
also comes with a direct way to help me format
second: json will turn into a solid object
that parseText
the 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
1.2 Using third-party libraries
We know that it Groovy
is fully compatible Java
, so Java
the third-party json
libraries that can be used (such as:, gson
or fastjson
whatever Groovy
can also be imported and used in China, but the one Groovy
that 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 ),
and then directly import the corresponding class in the script file and use the corresponding method.
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
is a Java
little different from ours , Java
in which you need to define a specific Entity class to parse, get the corresponding data after parsing, but Groovy
there is no need to define a specific entity class, we can directly get the data we want
2.xml detailed operation
The above mind map is Java
two ways to process data in xml format, and we Groovy
provide 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>
'''
Json
There was one in the operation before JsonSlurper
, then the corresponding one xml
will meet by chance.It XmlSlurper
also has a parse
method, which is basically the JsonSlurper
same as yours above .
For example, we want to output the name of the first book: Crazy Android Lectures, what should we do?
We found it is very simple and much more Java
convenient than ours , then what if we want to output the label attribute? For example, to obtain the available attribute of a book
2.2 Traverse XML
What should we do if we want to obtain xml
a collection of all the books whose author is Li Gang?
Here our logic should be to find the layers one by one, find books
the collection at the first layer response.value.books
, then traverse this books
, find each one book
, and take it the author
look is not called Gang
we see the results of our output is the correct result, but Groovy
in fact, provide a more simple method of traversing
deep traversal depthFirst
, we have achieved in this way under the effect of the above
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.
2.3 Generate XML
Groovy
You can also generate what you want xml
, for example, if we think about generating the following one, what xml
should 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 xml
has two nodes, one is langs
, the attributes are : type,count.mainstream
, langs
there 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 MarkupBuilder
Yes, a class will be used here . This class is xml
the core class for generating data.
If language
there is a node below, how to get it? language
Same as the node we specified
But in general, in actual development, we often convert entity objects into the xml
same way as above.
We first build a Language
class
//对应xml中的language节点
class Language {
String flavor
String version
String value
}
Then build a Langs
class
//对应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
,
we can also Json
combine it with us , the Json
string JsonSlurper
generates the entity class, and then MarkupBuilder
generates the correspondingxml
3. Detailed file operations
Import thinking above us Java
in the handling of files in Groovy
you can use these methods, but Groovy
also extends a number of more efficient and powerful methods (ResourceGroovyMethods)
then we have a few examples to the specific practices
we take on The examples here take this file as an example, it is automatically generated when the project is created, and the
creation File
object is Java
exactly the same as ours.
3.1 traverse the file
We first output the contents of this file, here we need to use eachLine
this method
3.2 Get all the contents of the file
This is the same as our output above
3.3 Get a list of each line of text
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
3.5 Copy files
We copied it line by line here, and we can also copy it all at once, we call this method
We see a file copied successfully, we open this file
It is exactly the same as the content of the source file.There
is also a place to note Java
here.We need to manually close the stream when reading and writing files in, but Groovy
we can omit this step in because we have done it for
us internally.Let's take a look at the withWriter
method first
Continue to go down,
let's look at finally
the method inside
3.6 Save the object to a file
A new method is used here withObjectOutputStream
, we use text reader和writer
, we use objectsstream
Let's write an example to verify that
we should pay attention here: this object must implement the serialization interface, otherwise it will report an error
3.7 Remove the object from the file
We take the one we just saved person
and we can see that it is the same as what we saved
OK, here we are finished like this, we will start learning Gradle
from the next article, see you in the next article