//Bean-->Json Json-->Bean
def pList = [new Person(name: 'John', age: 25)
, new Person(name: "Max", age: 26)]
def json = JsonOutput.toJson(pList)
println json//[{"age":25,"name":"John"},{"age":26,"name":"Max"}]
//格式化Json
println JsonOutput.prettyPrint(json)
/**
* JsonSlurper和JsonOutput相反,用于将Groovy对象转换为Json字符串。
* 它提供了很多parse方法,可以从文件、数组、字节流等各种地方转换对象,
* 这里调用的是parseText方法,从字符串中转换对象。
* 注意转换结果是一个Map,当然如果对象很简单,我们可以使用Groovy的Map解构用Map创建实际对象
* 用JsonSlurper的时候需要注意,
* 数组会被转换为ArrayList对象,而object会被转换为Map对象。在进行复杂对象处理的时候要留意这些返回值。
*/
def jsonSluerper = new JsonSlurper()
def p = jsonSluerper.parseText(json)
println p
//网络请求 需要用java的那一套
def getNetWork(String url) {
//发送请求
def connection = new URL(url).openConnection()
connection.setRequestMethod('GET')
connection.connect()
//耗时
def response = connection.content.text
//json-->bean
//def jsonSluper = new JsonSlurper()
//return jsonSluper.parseText(response)
println response
}
//def resp = getNetWork('https://blog.csdn.net/iblade')
//println resp
//XML 解析 深度遍历 广度遍历
def xmlStr = '''
<response version-api="2.0"/>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
'''
def xmlSlurper = new XmlSlurper()
def respXml = xmlSlurper.parseText(xmlStr)
//深度遍历 depthFirst()
def titles =respXml.depthFirst().findAll{
book-> return book.price>=30
}
println titles
//广度遍历
respXml.children().findAll {
node ->node.author=='J K. Rowling'&&node.@lang=='en'
}
//MarkupBuilder 生成xml
Gradle:4.groovy常见Json,xml,file处理
最新推荐文章于 2023-02-14 11:35:37 发布