Gradle:4.groovy常见Json,xml,file处理

//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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值